for loop in Scala code example

Example 1: how loop in scala

for ((name, count) <- names.zipWithIndex) {
    println(s"$count is $name")
}

Example 2: how loop in scala

for (i <- 1 to 10 if i < 4) println(i)

Example 3: how loop in scala

for (i <- 1 to 3) println(i)

Example 4: how loop in scala

for {
    i <- 1 to 10
    if i > 3
    if i < 6
    if i % 2 == 0
} println(i)

Example 5: how loop in scala

val nums = Seq(1,2,3)
val letters = Seq('a', 'b', 'c')
val res = for {
    n <- nums
    c <- letters
} yield (n, c)

Example 6: how loop in scala

val lengths = for (e <- names) yield {
    // imagine that this required multiple lines of code
    e.length
}