Read on to discover how to declare variables, the difference between var, val, and const val, and whether you should prefer immutability over mutability.
Declaring Kotlin variables
Variable declarations start with the val or var keyword, followed by the variable name.
valcreates an immutable variable, whose value cannot be changedvarcreates a mutable variable, whose value can be changed- For completeness sake, I'll mention that
const valcreates a constant, whose value cannot be changed and must be determined at compile time. We'll come back to those briefly in a future lesson
As is the case with function declarations, types are specified after declarations.
val country = "US" fun fetchAgeOfConsent(country: String) = 18 fun countBeers() = 5 //sampleStart fun main() { val ageOfConsent: Int = fetchAgeOfConsent(country) // ageOfConsent-- // Oh no you don't! var beersIHad: Int = countBeers() beersIHad += 10 // Not everything that compiles is a good idea } const val PI = 3.14159265358979323 //sampleEnd
Mutable vs. immutable in Kotlin
Prefer immutability over mutability.
Why? No but really, why? No but like, really, why?
It has been my experience that it is seldom necessary to use var in regular code, although coding exclusively with val sometimes requires more effort (and that’s okay).
One may encounter mutability in code that needs to be performant, or when defining low-level “atomic” operations on a data structure. For example, if you were implementing your own count(predicate) method, you would likely use a mutable counter internally.
Immutable types are safer from bugs, easier to understand, and more ready for change. Mutability makes it harder to understand what your program is doing, and much harder to enforce contracts.
Reading 9, 6.005: Software Construction at MIT
Read on to understand the difference between expressions and statements, and why Kotlin's when construct is a more powerful version of Java's switch.