Lesson contents

Scala — Choosing a value with if

In Scala, if and else form an expression. Its result can be assigned to a val, so each condition selects a value for the same immutable binding.

A simple example

Choose one value

  1. Start with n is 2
  2. Do this Choose by sign
  3. Result positive
The condition selects which word becomes the result.
Lesson.scala
object Lesson extends App {
    val n = 2
    val word = if (n > 0) "positive" else "other"
    println(word)
}
Output
positive
Advertisements

Classify a stock level

An if/else expression returns a value, so there is no separate mutable status variable. The zero case comes first because zero also satisfies the low-stock threshold.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.

Run the example

Scala 2.13 with JDK 11 or later. 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 stock = 3
    val status =
      if (stock == 0) "sold out"
      else if (stock <= 5) "order soon"
      else "in stock"
    println(status)
  }
}
Output
order soon

The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.

Try it yourself

Try the boundary values 0, 5, and 6.

Check your answer

They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.

Tour of Scala

Related tags

  • Scala
  • conditions
  • branching
  • comparison