Everything is an expression
In Java or C, if is a statement: it does something but has no value, so you declare a variable first and assign it inside each branch. In Scala, if is an expression: it evaluates to the value of whichever branch ran, and you can put that value straight into a val. The same is true of blocks, match, try and for ... yield. This one idea is why Scala code needs so few vars.
@main def run(): Unit =
val temp = 31
val feel = if temp > 30 then "hot" else "fine"
println(feel)
val bmi =
val weightKg = 70.0
val heightM = 1.75
weightKg / (heightM * heightM)
println(f"$bmi%.1f")
println(if temp % 2 == 0 then "even" else "odd")hot
22.9
oddThe indented lines under val bmi = are a block. A block evaluates to its last expression; weightKg and heightM exist only inside it.
Add a third branch with else if temp < 15 then "cold" and change temp to 10.
Statement style (Java habit)
var label = ""declared firstif (n > 0) label = "pos" else label = "neg"- The compiler cannot check every branch assigned it
- Needs a
var
Expression style (Scala)
val label = if n > 0 then "pos" else "neg"- One line, one name, assigned once
- The compiler checks the branch types
- Stays a
val
cond ? a : b. It does not need one: if cond then a else b already is the ternary. The return keyword exists too, but idiomatic Scala almost never uses it — the last expression of a method is its result.if without else has no value to give
@main def run(): Unit =
val stock = 0
val label: String = if stock > 0 then "in stock"
println(label)-- [E007] Type Mismatch Error: Main.scala:3:22
3 | val label: String = if stock > 0 then "in stock"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| Found: Unit
| Required: String
|
| Maybe you are missing an else part for the conditional?
1 error found
Compilation failedWhen stock is 0 the if has nothing to return, so an if without else always has type Unit. A Unit cannot go into a String. The compiler even guesses the cause for you.
Give every expression-style if an else, so there is a value on both paths.
@main def run(): Unit =
val stock = 0
val label: String = if stock > 0 then "in stock" else "sold out"
println(label)