for-comprehension is construction in Scala language allowing easy iteration over one or more collections.
Before we see some examples of for-comprehension lets first define following lists:
val list1 = List("a", "b")
val list2 = List("c", "d")
val list3 = List("e", "f")
Now we can see first example. It is imperative form of for-comprehension. It iterates over each of list and for each combination executes 'println' statement:
for { x <- list1; y <- list2; z <-list3 } println(x+y+z)
The result is:
ace
acf
ade
adf
bce
bcf
bde
bdf
Second example is functional form of for-comprehension. It uses yield keyword to create and return a list:
for { x <- list1; y <- list2; z <-list3 } yield x+y+z
The result is:
List[String] = List(ace, acf, ade, adf, bce, bcf, bde, bdf)