typestar

for loops in Scala

Three shapes of for: over a collection, over .indices, and with two generators.

val stalls = Vector("bread", "honey", "cider", "wool")

// for ... do runs the body once per element.
def announceStalls(): Unit =
  for stall <- stalls do
    println("now open: " + stall)

// .indices gives the valid positions of a sequence.
def numberStalls(): Unit =
  for i <- stalls.indices do
    println(s"${i + 1}. ${stalls(i)}")

// Two generators nest: the second runs inside the first.
def stallGrid(): Unit =
  for
    row <- 1 to 3
    col <- 1 to 2
  do println(s"pitch $row-$col")

How it works

  1. for stall <- stalls do walks the Vector and prints one line per element.
  2. for i <- stalls.indices do loops over positions instead, so stalls(i) can be numbered.
  3. The last loop nests the generators row <- 1 to 3 and col <- 1 to 2 over a single do println(s"pitch $row-$col").

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
472
Tokens
95
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 3 of 3 in Expressions, step 6 of 27 in Language basics.

← Previous Next →

for loops in other languages