Conditionals
Bodies of Slang Conditionals are Blocks
Conditional statements in Slang are a bit more restrictive than in
Scala: statements appearing in the if
or else
branch of must
appear in a block (even if the branch consists only of a single statement):
// Illustrating Conditionals -- branches must be blocks
if (B.random) { // conditional statement requires a block on its branches
println("Randomly printed")
}
val x3 = Z.random
if (x3 > 100) {
val y:Z = x3 + 22
println("If branch: ", y)
} else { // need a block, even though there is only one statement in else branch
println("Else branch")
}
Else - If
An exception to “branch bodies are blocks” rule is chaining conditionals together with an
else if
: the if
statement in the else
branch does not have to be
wrapped in a block:
// Nested/chained conditional
val x4 = Z.random % 3
if (x4 == 2) {
println("A")
} else if (x4 == 1) { // note "if" itself doesn't have to be in a block
println("B")
} else {
println("C")
}
Conditional Expressions
In conditional expressions, the contents of the if
and else
branches do not have to be in blocks when there is only a single
expression/statement in the branch:
// Conditional expression -- no blocks needed
val x5: Z = if (B.random) x3 else -x3 // conditional expression (no blocks)
Blocks may be used in conditional expression branches to include statements in a branch before the final value-producing expression in the branch:
// conditional blocks
val x6: Z =
if (B.random) { // conditional block expression
println("5") // statement
5 // expression producing value for branch
} else {
println("1")
6
}