liveBook · Manning

Block expression

As explained in Functional Programming in Scala, Second Edition

A Scala sequence of statements and expressions whose value is the value of its last expression.

A block expression groups multiple Scala statements into one expression. Statements can be separated by newlines or semicolons, and curly braces are often optional. The block’s value is the value produced by its final expression. section 2.1

Naming an intermediate value

In `formatAbs`, `val msg = "The absolute value of %d is %d"` binds an immutable intermediate value. The final expression, `msg.format(x, abs(x))`, becomes the block’s value and therefore the method’s result. The block keeps preparation and final computation together without an explicit `return`. section 2.1

private def formatAbs(x: Int) =
  val msg = "The absolute value of %d is %d."
  msg.format(x, abs(x))                        #1

Inspect the compact Scala definition showing an intermediate `val` followed by the expression that determines the block result. section 2.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines syntax, statement separation, optional braces, immutable bindings, and last-expression evaluation through one worked method.
Examples
Uses `formatAbs` to bind a message and return its formatted result.
What it assumes
Assumes basic Scala methods and values while teaching block syntax and evaluation directly from a small program.
What you can do after
Understand how Scala methods return the value of a multistatement block without requiring `return`.
How it connects
Connects blocks to methods, expressions, immutable variables, and pure functions.

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.