Lesson contents

Scala — For loops and indexed traversal

A Scala for loop can iterate over positions and use them to read values from an indexed collection. for without yield is useful for reporting a result by side effect.

A simple example

Print the numbers 1 to 3

  1. Start with Start at 1
  2. Do this Visit 1, 2, 3
  3. Result 1 → 2 → 3
Each pass prints one number on its own line. After 3 the loop has no more values to visit.
Lesson.scala
object Lesson extends App {
    for (n <- 1 to 3) {
        println(n)
    }
}
Output
1
2
3
Advertisements

Number each nonempty bin in order

Traverse bin quantities in their original order and retain each position when reporting nonempty bins. Human-readable bin numbers start at one. indices supplies valid zero-based positions and stays empty for an empty collection. Add one only when displaying the bin number.

Bin 1: 3 items. Bin 2: Empty. Bin 3: 5 items.
Keep the printed bin numbers

Three supply bins contain 3, 0 and 5 items. Skip printing the empty middle bin but keep its position in the sequence. The last line must still refer to bin 3.

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 bins = Vector(3, 0, 5)
    for (index <- bins.indices) {
      if (bins(index) > 0) {
        val number = index + 1
        val quantity = bins(index)
        println(s"bin $number: $quantity")
      }
    }
  }
}
Output
bin 1: 3
bin 3: 5

The first and third bins have stock. The empty second bin is omitted but still occupies position two.

Try it yourself

What should the report contain for three empty bins?

Check your answer

It contains no lines. Every position is visited and each quantity fails the positive-stock test.

Scala language specification

Related tags

  • Scala
  • for loops
  • iteration
  • positions