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

if as an Expression

In Scala, an if can hand you back an answer, like a question that returns this or that. So you can store the result straight in a variable.

In this page:

  1. if as an Expression
Syntax
scala
val result = if (condition) value1 else value2

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving out the else branch and expecting a value, when the result becomes Unit or Any instead of the type you wanted.
  2. Writing if (x > 5) "big" else 0, which makes the result type Any because the branches have different types.
  3. Using return in an if when the if itself produces the value.
🔒

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.