Lesson contents

Scala — Comparisons and short-circuit operators

Boolean && in Scala short-circuits. Check both ends of an index before asking an indexed sequence for its element.

A simple example

Test two conditions

  1. Start with n is 2
  2. Do this Greater than 0 and less than 3?
  3. Result yes
Both comparisons succeed, so the program prints yes.
Lesson.scala
object Lesson extends App {
    var n = 2
    if (n > 0 && n < 3) {
        println("yes")
    }
}
Output
yes
Advertisements

Operator examples

Operation Expression Result
Integer division 7 / 2 3
Remainder 7 % 2 1
Comparison 5 >= 5 true
Equality 3 == 4 false
Logical conjunction true && false false
Bit mask 6 & 3 2

Guard an indexed lookup

Combine comparisons with a short-circuiting logical operator. Check that a zero-based index is within bounds before reading the element at that index. Parentheses on stock(i) call the sequence's apply method. Checking the upper bound and the nonnegative lower bound avoids an out-of-range access.

Shelf quantities: 2 and 5. Order needs: At least 5. Second shelf: 5 available.
Look up a shelf safely

A stock scanner receives a shelf position before it knows whether that shelf exists. Check the bounds first. Only an existing shelf with at least five units can supply the order.

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 stock = Vector(2, 5)
    for (i <- List(-1, 1, 2)) {
      val take = i >= 0 && i < stock.length && stock(i) >= 5
      println(if (take) "take" else "skip")
    }
  }
}
Output
skip
take
skip

Only index 1 is in bounds in the three trial lookups. Its value is exactly the threshold of 5, so it passes the inclusive comparison.

Try it yourself

Try index 0, then change its value from 2 to 5. How does its classification change?

Check your answer

Index 0 is valid in both cases. It changes from skip to take when its value reaches 5.

Scala language specification

Related tags

  • Scala
  • operators
  • short-circuit evaluation
  • bounds checks