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:
Syntax
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
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
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
- Leaving out the
elsebranch and expecting a value, when the result becomesUnitorAnyinstead of the type you wanted. - Writing
if (x > 5) "big" else 0, which makes the result typeAnybecause the branches have different types. - Using
returnin anifwhen theifitself produces the value.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: