Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

2.3 Block Expressions and Assignments

In Java or C++, a block statement is a sequence of statements enclosed in { }. You use a block statement whenever you need to put multiple actions in the body of a branch or loop statement.

In Scala, a { } block contains a sequence of expressions, and the result is also an expression. The value of the block is the value of the last expression.

This feature can be useful if the initialization of a val takes more than one step. For example,

val distance = { val dx = x - x0; val dy = y - y0; sqrt(dx * dx + dy * dy) }

The value of the { } block is the last expression, shown here in bold. The variables dx and dy, which were only needed as intermediate values in the computation, are neatly hidden from the rest of the program.

In Scala, assignments have no value—or, strictly speaking, they have a value of type Unit. Recall that the Unit type is the equivalent of the void type in Java and C++, with a single value written as ().

A block that ends with an assignment statement, such as

{ r = r * n; n -= 1 }

has a Unit value. This is not a problem, just something to be aware of when defining functions—see Section 2.7, “FunctionsFunctions as Values,” on page 20.

Since assignments have Unit value, don’t chain them together.

x = y = 1 // No

The value of y = 1 is (), and it’s highly unlikely that you wanted to assign a Unit to x. (In contrast, in Java and C++, the value of an assignment is the value that is being assigned. In those languages, chained assignments are useful.)

  • + Share This
  • 🔖 Save To Your Account