liveBook · Manning

Val

As explained in Functional Programming in Scala, Second Edition

A Scala declaration form that binds a name immutably to a value.

A val declaration binds a name immutably to a value. In formatAbs, val msg gives the formatted string a name before msg.format uses it, separating local data from the surrounding computation. section 2.1

Naming an intermediate value

private def formatAbs(x: Int) = val msg = "The absolute value of %d is %d." msg.format(x, abs(x)) The declaration evaluates the string expression, binds its result to msg, and makes that value available to the following expression. section 2.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines val through one concrete binding example and stops short of broader declaration rules or implementation details.
Examples
Uses msg to hold a format string before calling msg.format inside formatAbs.
What it assumes
Assumes basic familiarity with Scala methods and expressions while introducing val within a complete program.
What you can do after
Build it from scratch by naming an intermediate value in a Scala method and using that value in a subsequent expression.
How it connects
Connects val with methods, expressions, pure functions, and string formatting.

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.