An immutable variable is a named binding whose association with its value cannot be reassigned after initialization. In Scala, val introduces this kind of binding: once msg refers to a String, the name continues to refer to that same value within its block. section 2.1
Scala also supports mutable variables with var, but val is used more frequently. The compiler rejects an attempt to assign msg a different value in the same block, making the binding predictable while the surrounding method remains an expression-valued computation. section 2.1
Naming a format string
private def formatAbs(x: Int) = val msg = "The absolute value of %d is %d" msg.format(x, abs(x)) section 2.1
Listing 2.1 A simple Scala program
// A comment!
/* Another comment */
/** A documentation comment */
object MyProgram: #1
def abs(n: Int): Int = #2
if n < 0 then -n #3
else n
private def formatAbs(x: Int) = #4
val msg = "The absolute value of %d is %d" #5
msg.format(x, abs(x)) #6
@main def printAbs: Unit = #7
println(formatAbs(-42))
Inspect the complete Scala program and see the immutable msg binding used inside a private method. section 2.1
