Andrew Binstock (2) [Avatar] Offline
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!

Johnny N. (3) [Avatar] Offline
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
@413596 Thanks!