← Back to Scala Course | Chapter 4: Control Flow | Lesson 1 of 7

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:

  1. if / else
Syntax
scala
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

markup
object Main extends App {
  val score = 72

  if (score >= 90) {
    println("A")
  } else if (score >= 70) {
    println("B")
  } else {
    println("C")
  }
}
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. Writing else if conditions in the wrong order, such as checking score >= 70 before score >= 90, so the first true branch hides the later ones.
  2. Using = instead of == in the condition, which does not compile.
  3. Putting else on a new line after } in older Scala 2 code where it may not attach to the if, 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:

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.