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

if / else

In this page:

  1. if / else

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")
  }
}
🔒

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.