4 Final Variables
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
.
Exercise
Edit the code on the left, so it will run (either change theval
back to var
, remove the reassignment to x
or assign the result of the expression in line 3 to a different val
or var
)
Note: Prefer using `val` over `var` (and immutable objects over mutable ones). There are many benefits that are out of the scope of this small tour.