if / else
In this page:
if / else
An if statement runs a block only when its condition is true, and an optional else runs otherwise, chaining with else if for multiple conditions. As covered earlier, if/else is also an expression that produces a value. Braces are optional for a single statement but recommended for clarity in multi-line blocks.
Note: Chain conditions with else if instead of nesting separate if blocks for multi-way branching.
Example: if / else
object Main extends App {
val score = 72
if (score >= 90) {
println("A")
} else if (score >= 70) {
println("B")
} else {
println("C")
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: