Ad space (banner)
Lesson 5 / 20

Branching (the if expression)

This lesson covers how to write an if statement in Scala.

if / else if / else branches on a condition. What sets Scala apart is that its if is also an expression, so the result can be assigned to a variable.

The sample code uses if / else if / else to print one of three messages depending on score.

A common early stumble is not noticing that an if can return a value, and using it only as a statement the way other languages do. You can write val result = if (score >= 60) "Pass" else "Fail", much like a ternary operator.

In professional work, leaning on this expression form to write conditional assignment concisely is a hallmark of idiomatic Scala.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)