if as an Expression
In this page:
if as an Expression
Unlike many languages where if is purely a statement, Scala's if/else is an expression that produces a value, which can be assigned directly to a val. Both branches should generally produce values of compatible types, since the whole expression has one combined type. This lets you avoid the mutable-variable-plus-assignment pattern common in other languages.
Note: Because if is an expression, val result = if (cond) a else b is idiomatic Scala, replacing what would need a mutable variable in many other languages.
Example: if as an Expression
object Main extends App {
val age = 20
val category = if (age >= 18) "adult" else "minor"
println(category)
val max = if (5 > 3) 5 else 3
println(max)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: