Why are `private val` and `private final val` different?

So, this is just a guess, but it was a perennial annoyance in Java that final static variables with a literal on the right-hand side get inlined into bytecode as constants. That engenders a performance benefit sure, but it causes binary compatibility of the definition to break if the “constant” ever changed. When defining a final static variable whose value might need to change, Java programmers have to resort to hacks like initializing the value with a method or constructor.

A val in Scala is already final in the Java sense. It looks like Scala’s designers are using the redundant modifier final to mean “permission to inline the constant value”. So Scala programmers have complete control over this behavior without resorting to hacks: if they want an inlined constant, a value that should never change but is fast, they write “final val”. if they want flexibility to change the value without breaking binary compatibility, just “val”.

Leave a Comment