liveBook · Manning

Immutable variable

As explained in Functional Programming in Scala, Second Edition

A named binding whose association with its value cannot be reassigned after initialization.

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

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines val, explains reassignment failure, and contrasts it with var in a method block.
Examples
Uses the msg binding in formatAbs to reuse a format string while computing an absolute-value message.
What you can do after
Apply it via Scala's val to name a string and prevent reassignment within a block.
How it connects
Connects val with Scala blocks, methods, expressions, and mutable variables declared with var.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.