Kotlin: val is read-only not immutable
You might often have read/heard that the Kotlin val keyword is for immutable fields.
Immutable is an object/variable whose state cannot be modified after it is created; that’s not true with val fields: as stated in the Kotlin Reference val is intended to define read-only (a.k.a. assign once) fields, in other words “values”, while var is used for mutable variables.
There’s a subtle difference between read-only and immutable. The former cannot be re-assigned once initialized, for the latter there is no way to change the state of the object/field.
Let’s suppose we have a Box class with its width, height and length properties
Now imagine to add two more properties (availableSpace and usedSpace) to the Box object
and that availableSpace is defined as a computed value based on the box size and the space already occupied by the stuff you put into the box.
Suppose we created the box object above, initially the availableSpace property value will be 40000.
But what happens if we put something inside the box, let’s say 3 comic books of size 16 x 21 x 1?
As you can see, though being read-only, box.availableSpace changed its value over time, thus it cannot be said to be immutable.