Lesson contents

Scala — If, else if, and else

Scala if can choose which action executes. A guard for invalid input should precede any broader condition that could otherwise accept it.

A simple example

Follow one branch

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
Lesson.scala
object Lesson extends App {
    var n = 2
    if (n > 0) {
        println("yes")
    } else {
        println("no")
    }
}
Output
yes
Advertisements

Classify a stock request

Check whether a request is positive before comparing it with the available stock. Select one action for an invalid, fillable, or deferred request. These branches call println and produce Unit. A separate lesson uses the same conditional construct to compute and store a value.

Available: 3 calculators. Request exactly 3: Accept. Request 8: Defer.
Decide which orders to fill

The equipment desk has three calculators to lend. A request for a negative quantity is invalid, three can be filled exactly, and eight must wait. Each request produces one decision.

Run the example

Use Scala 2.13. Run these commands from the directory containing the example.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
    val available = 3
    for (request <- List(-1, 3, 8)) {
      if (request <= 0) {
        println("invalid")
      } else if (request <= available) {
        println("accept")
      } else {
        println("defer")
      }
    }
  }
}
Output
invalid
accept
defer

With three in stock, −1 is invalid, 3 can be filled exactly, and 8 must be deferred. Only the first matching branch runs.

Try it yourself

What should happen for a request of zero?

Check your answer

The first branch rejects it as invalid. Checking the stock limit first would incorrectly treat zero as fillable.

Scala language specification

Related tags

  • Scala
  • if
  • else
  • branch order