Scala: for loop vs. for comprehension


17. 04. 2018 |

This is a for comprehension:

val words = List("Hello", "World")

for {
    word <- words
    char <- word
} yield char

This is also technically a for comprehension, but used as a for loop. It can have side-effects:

// Right
for (word <- words; char <- word) {
    println(char)
}

// Wrong
for {
    word <- words
    char <- word
} {
    println(char)
}