Vals and vars
Kotlin has two keywords for declaring variables, val
and var
. The var
is a mutable variable, which is, a variable that can be changed to another value by reassigning it. This is equivalent to declaring a variable in Java:
val name = "kotlin"
In addition, the var
can be initialized later:
var name: String name = "kotlin"
Variables defined with var
can be reassigned, since they are mutable:
var name = "kotlin" name = "more kotlin"
The keyword val
is used to declare a read-only variable. This is equivalent to declaring a final variable in Java. A val
must be initialized when it is created, since it cannot be changed later:
val name = "kotlin"
A read only variable does not mean the instance itself is automatically immutable. The instance may still allow its member variables to be changed via functions or properties, but the variable itself cannot change its value or be reassigned to another value.