← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 6 of 7

if as an Expression

In this page:

  1. if as an Expression

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

markup
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)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.