Blocks
Blocks - Local Scope for Variable Declarations and Command Aggregation
Slang includes Scala’s notion of a block, which uses curly braces
{ ... }
to introduce a local scope for variables and aggregation
of commands within the scope.
Here are some examples (using a coding style that omits semicolons by
relying on Scala’s line-orientation):
// Illustrating "blocks" - sequence of statements in { ... }
val x1 = Z.random
{ // a block is a sequence of statements with its own scope
println("Inside block")
val y = x1 + 1 // can refer to vars (e.g., x1) outside scope
assert(y > x1)
} // y is no longer available
The block above illustrates a block with a sequence of print, variable
declaration, and assertions. The block introduces a local variable
y
which can be used within the block after the declaration, but it
not visible outside of the block. Variables in scope immediately
outside of the block such as x1
are also visible in the block.
Blocks as Expressions – Yielding Values
// Illustrating a block expression - produces a value for val/var definition or assignment
val x2: Z = { // an explicit type is required for the declared identifier when a block expression is used
println("Inside block expresion")
x1 + 2 // produces the value to give to x2
}
This block illustrates that a block can have a sequence of several statements/expressions and then conclude in an expression that gives a value for the entire block (this type of block is referred to as an “expression block”). In any block, expressions can also appear any place in the sequence but the value of any expression not appearing last in the sequence is ignored.
When used in declarations, the identifier being declared must be given an explicit type.