Variables · 5 of 42
Final variables are declared using the val keyword (a final variable is a variable that can’t be reassigned).
The code on the left looks almost exactly like in the previous step, with one small change. The var was changed to val.
Try to run the code on the left, the compiler should complain on line 3, since we are trying to reassign x which is a val.
val back to var, remove the reassignment to x, or assign the result of the expression in line 3 to a different val or var).
val over var (and immutable objects over mutable ones). There are many benefits that are out of the scope of this small tour.
val x = 1 + 2 //val instead of var println(x) x = 3 * 4 //error: reassignment to val println(x)