Expressions and if
In Scala a block is an expression: it has a type and a value, and the value is what its last expression evaluates to. An if is a block, so it returns the branch it takes, and a method whose body is an if needs no return.
if with then and else
Scala 3 writes if with then, which makes the end of the condition visible. The branches may be expressions on one line or indented blocks, and the value of the whole if is the value of the branch that ran:
expressions.scala
@main def expressions(): Unit =
val temperature = 21
val feeling =
if temperature > 25 then "hot"
else if temperature > 15 then "mild"
else "cold"
println(feeling)
val label = if temperature >= 18 then "warm" else "cool"
println(label)
val status = {
val base = if temperature > 0 then "above" else "below"
s"$base zero"
}
println(status)
scala-cli run --server=false expressions.scala
mild
warm
above zero
There is no ternary operator, and none is needed: the if is already the expression ? : would be. The braces in the third block are allowed and do not change the meaning; the course writes an indented block without them, and the next-but-one lesson explains when braces are still the clearer choice.
A branch as the body of a method
The value of the last expression is the result of the method, so an if chain at the end of a method is a return value without the keyword. The method below is total: every Int takes one of the three branches.
sign.scala
def sign(n: Int): String =
if n > 0 then "positive"
else if n < 0 then "negative"
else "zero"
@main def signs(): Unit =
List(3, -3, 0).foreach(n => println(s"$n is ${sign(n)}"))
scala-cli run --server=false sign.scala
3 is positive
-3 is negative
0 is zero
The declared result type String is what makes the method total: a branch of another type is a compile error at the method, not a surprise at the call. That is also why an if without an else is a Unit expression when its branch returns nothing, and the compiler says so.
Statements are expressions too
Assignment, println and a for loop are expressions of type Unit, which is why they can sit in the middle of a block. The value of a sequence is the value of its last expression; every earlier one is evaluated for its effect. A method that ends with println therefore returns (), and a declared String result after it is a compile error rather than a silent null.
Related
- Loops and for comprehensions: the expression that repeats.
- Methods and parameters: the result type of a method.
- Enums and sealed hierarchies: the types where a match replaces a chain of if.
- Values and types: Unit and the type of a block.
Автор статьи: Arthur Isaev