Expressions over Statements
Everything is an expression.
Expressions vs Statements
A statement does something but returns nothing useful. An expression evaluates to a value.
In Scala, almost everything is an expression. This is a core idea that shapes how you write code.
if Is an Expression
In many languages if is a statement. In Scala, if/else returns a value, so you can assign it directly to a val.
No need for a separate variable assigned in each branch.
object Main {
def main(args: Array[String]): Unit = {
val temp = 30
val label = if (temp > 25) "hot" else "mild"
println(label)
}
}All lessons in this course
- Using the REPL
- val, var and Types
- Expressions over Statements
- String Interpolation