Expressions over Statements
Everything returns a value.
Everything Is an Expression
In many languages, if and blocks are statements that do something but produce no value. In Scala they are expressions that evaluate to a value.
This shift is at the heart of functional programming in Scala.
val max = if (3 > 2) 3 else 2if as an Expression
A Scala if/else returns the value of the branch that runs. You can assign that result directly to a val.
No need for a mutable variable that you set inside the branches.
object Main extends App {
val temp = 18
val label = if (temp > 20) "warm" else "cool"
println(label)
}All lessons in this course
- val vs var
- Basic Types and Literals
- Type Inference
- Expressions over Statements