if / else
if and else let the program choose what to do, like 'if it is cold wear a coat, else wear a t-shirt'. The block runs only when the question is true.
In this page:
Syntax
if (condition) {
// body
} else if (other_condition) {
// body
} else {
// body
}
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
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
- Writing
else ifconditions in the wrong order, such as checkingscore >= 70beforescore >= 90, so the first true branch hides the later ones. - Using
=instead of==in the condition, which does not compile. - Putting
elseon a new line after}in older Scala 2 code where it may not attach to theif, when keeping} else {on the same line is safe.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: