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
for stall <- stalls dowalks theVectorand prints one line per element.for i <- stalls.indices doloops over positions instead, sostalls(i)can be numbered.- The last loop nests the generators
row <- 1 to 3andcol <- 1 to 2over a singledo println(s"pitch $row-$col").
Keywords and builtins used here
UnitVectorannounceStallsdefdofornumberStallsstallGridval
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.
Step 3 of 3 in Expressions, step 6 of 27 in Language basics.