home search about rss feed twitter ko-fi

‘for’ Loops (Scala 3 Video)

The for loop is similar to other languages. It’s used for side effects, such as printing, mutating var fields, mutating mutable collections.

Basic syntax:

val ints = List(1, 2, 3)

for i <- ints do println(i)

for
    i <- ints
do
    println(i)
  • In those examples, ints is a generator.
  • Can also have multiple generators:
// STEP 1
for
    i <- 1 to 2
    j <- 'a' to 'b'
do
    println(s"i = $i, j = $j")

// STEP 2
for
    i <- 1 to 2
    j <- 'a' to 'b'
    k <- 1 to 10 by 5
do
    println(s"i = $i, j = $j, k = $k")

for loop with a Map:

val statesMap = Map(
    "AK" -> "Alaska",
    "AL" -> "Alabama", 
    "AR" -> "Arizona"
)

for
    (k, v) <- statesMap
do
    println(s"$k stands for $v")

Update: All of my new videos are now on
LearnScala.dev