Andrew Binstock (2) [Avatar] Offline
#1
In the book, it states on page 20 (of the PDF): "There are two keywords to declare a variable: val (from value)—Immutable reference. A variable declared with val can’t be reassigned after it’s initialized. It corresponds to a final variable in Java."

However, from this thread on Reddit[1], it seems that val does not actually mean immutable but rather read-only. Likewise, the official docs do not describe val as being immutable.

Perhaps you can clarify what exactly val promises. I think this is especially important here at this first definition.

I'm enjoying the book. Good work!

[1] https://www.reddit.com/r/Kotlin/comments/50ge90/kotlin_val_does_not_mean_immutable_it_just_means/
Johnny N. (3) [Avatar] Offline
#2
Remember, the text says "immutable reference". A better way to think of val is to first think of how objects and references work in the JVM. Consider the following code:
val sb = StringBuilder()
sb.append("a")  // ok
sb.append("b")  // ok
sb.append("c")  // ok

Although the underlying properties of the the object may change, the code here works because the reference to the object in memory of sb does not change.


Now, if I try to change the reference of a val as in this code snippet:
val sb = StringBuilder()
sb.append("abc") // ok

// Attempt to create new object and storing it in sb
sb = StringBuilder("prefix") // !! NOT okay

Line 5 breaks the promise of val in that we are trying creating a new object (thus a new reference to an object in memory) and using sb to refer to it (changing the reference).

Hope this explanation helps.
Andrew Binstock (2) [Avatar] Offline
#3
@413596 Thanks!