In the examples above you may have noticed that we having been using the keyword
declaring our variables—even when the compiler can infer the type for us.
One thing that this accomplishes is to distinguish between initialization and reassignment:
So we’re not left with the same confusion produced by Python. That seems like a worthwhile tradeoff for a bit of extra syntax.
var also means something—specifically it means that the
variable is mutable, which means that its value can be changed.
If you’re used to Java and Python you’re used to working with mutable variables. This is the default in Java:
And also normal in Python:
i = 5 i = 10
But in many ways Kotlin encourages you to use immutable variables.
You can create them using the
val keyword in place of
good for a variety of reasons
which we’ll return to later.
But for now one of our goals will be to try and avoid use of
Happily, Kotlin provides us with a bunch of nice idioms for accomplishing
this—some of which we’ll see very soon.
Immutability also works quite nicely with type inference.
val variables must be set when they are declared, Kotlin can almost
always infer their types correctly, rendering explicit types unnecessary.
For those that know their Java well, you’ll be aware that Java does provide a
final keyword that behaves a bit like
Too bad it represents extra syntax clutter…
And, as a bit of a preview, Kotlin provides really nice ways of avoiding places where you might normally need to use mutable variable. For example, consider this bit of Java:
should has to be declared outside the
if but modified inside, it
final in Java.
In Kotlin we have an elegant way around this problem using
which we will cover later.