Table of Contents
Besides having a bad memory, I haven’t been able to work with Scala much recently, so I’ve been putting together this list of for
loop examples.
This page is a work in progress, and as of tonight I haven’t tested some of the examples, but ... if you’re looking for some Scala for
loop examples — technically called a for-comprehension or for-expression — I hope these examples are helpful.
Example data structures
Before getting into the examples, it helps to have some simple, common data structures at our disposal, so I’ll use these data structures in the examples that follow:
val names = Seq("chris", "ed", "maurice")
val nums = Seq(1, 2, 3)
I’ll add a few more data structures below as needed, such as in the Map
examples.
Basic for-loop examples
First, a few basic Scala for
loops:
for (n <- names) println(n)
for (n <- names) println(n.capitalize)
for (n <- names) {
// imagine this requires several lines
println(n.capitalize)
}
Using generators in for-loops
Next, here’s a for
loop that uses a single generator:
for (i <- 1 to 3) println(i)
Multiple generators:
val nums = Seq(1,2,3)
val letters = Seq('a', 'b', 'c')
val res = for {
n <- nums
c <- letters
} yield (n, c)
If you paste that block of code in the REPL, it will yield this result:
res: Seq[(Int, Char)] = List((1,a), (1,b), (1,c),
(2,a), (2,b), (2,c),
(3,a), (3,b), (3,c))
Scala for-loop generators with guards
Here’s one generator with one guard (an if
condition), on one line:
for (i <- 1 to 10 if i < 4) println(i)
Here’s the same thing on multiple lines:
for {
i <- 1 to 10
if i < 4
} println(i)
This example shows several guards:
for {
i <- 1 to 10
if i > 3
if i < 6
if i % 2 == 0
} println(i)
Scala for/yield examples (for-expressions)
A common use case is to use a for
loop with yield
to create a new data structure from an existing data structure. Here’s a simple example:
val names2 = for (e <- names) yield e.capitalize
Here’s a multiline version:
val lengths = for (e <- names) yield {
// imagine that this required multiple lines of code
e.length
}
Note that for/yield is the same as a basic map
example:
val out = for (e <- names) yield e.capitalize
val out = names.map(_.capitalize)
Scala for-loop counters (and zip, zipWithIndex)
You can use a counter in a for
loop like this:
for (i <- 0 until names.length) {
println(s"$i is ${names(i)}")
}
For a zero-based counter you can also use zipWithIndex
:
for ((name, count) <- names.zipWithIndex) {
println(s"$count is $name")
}
Beware: zipWithIndex
creates a new sequence from the existing sequence, you may want to call view
before invoking zipWithIndex
:
val zwi2 = names.view.zipWithIndex
The zipWithIndex
counter starts at 0
; zip
lets you control where the counter starts from:
for ((name,count) <- names.view.zip(Stream from 1)) {
println(s"$count is $name")
}
Can also use foreach
with zipWithIndex
:
names.zipWithIndex.foreach { d =>
println(s"${d._2} is ${d._1}")
}
Note that these examples work as shown because zip
and zipWithIndex
both return a sequence of Tuple2
elements.
Using a for loop with a Scala Map
Here are some examples of how to use a for
loop with a Scala Map
(mutable or immutable):
val nameMap = Map("firstName" -> "Ed", "lastName" -> "Chigliak")
for ((k,v) <- nameMap) {
println(s"key: $k, value: $v")
}
val result = for ((k,v) <- nameMap) yield {
s"key: $k, value: $v"
}
println(result)
That’s not the most useful example because result
ends up as a List
:
List(key: firstName, value: Ed, key: lastName, value: Chigliak)
but I can’t think of a good example right now, and I wanted to show a for/yield example with a Map
.
Here’s another example with for
and a Map
:
val ratings = Map(
"Lady in the Water"-> 3.0,
"Snakes on a Plane"-> 4.0,
"You, Me and Dupree"-> 3.5
)
for ((name,rating) <- ratings) println(s"Movie: $name, Rating: $rating")
That’s the same as the first Map
example, but I wanted to show a Map
with foreach
:
ratings.foreach {
case(movie, rating) => println(s"key: $movie, value: $rating")
}
ratings.foreach(x => println(s"key: ${x._1}, value: ${x._2}"))
ratings.keys.foreach((movie) => println(movie))
ratings.keys.foreach(println)
ratings.values.foreach((rating) => println(rating))
Multiple futures in a for loop
You can use a Scala Future
with a for
comprehension, but you have to make sure you create the future(s) before the comprehension, like this:
val result1 = Future { do1() }
val result2 = Future { do2() }
val result3 = Future { do3() }
Do that first, then merge the futures’ results inside the for
loop:
val result = for {
r1 <- result1
r2 <- result2
r3 <- result3
} yield (r1 + r2 + r3)
For more details on this, see my How to use multiple Scala Futures in a for loop example.
foreach examples
You can also use the foreach
method on the Scala collections classes:
names.foreach(println)
names.foreach(e => println(e.toUpperCase))
names.foreach {
// imagine this requires multiple lines
e => println(e.toUpperCase)
}
See the Map
examples above for examples of using foreach
with a Map
.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Summary
As a quick summary, if you wanted to see some Scala for
loop examples in a concise format, I hope this is helpful. For more details on the for
comprehension, see these links:
- How to loop over a Scala collection with a for loop
- Scala: How to create a "for comprehension" (for/yield loop)
- How to loop over Scala collections with for and foreach
- How to loop over a Scala collection with a for loop
- Scala: How to use zipWithIndex or zip to create loop counters
- Scala: How to use zipWithIndex or zip to create loop counters
- How to traverse a Map in Scala (for loop, foreach)