Scala offers list comprehensions, which are a simple way to create lists. These are often used to convert one list into another, while applying some change to each entry. List comprehensions can also filter a list.
For example, we can determine the length of words in a sentence:
val x = "The quick brown fox jumps over the lazy dog".split(" ")
y: Array[Int] = Array(3, 5, 5, 3, 5, 4, 3, 4, 3)
Then, we can filter it to only long words:
val z = for (i <- x if i.length > 4) yield i
z: Array[String] = Array(quick, brown, jumps)
Let’s say we had a second sentence, and we wanted to find the words that are in both.
We can do this with a for comprehension:
For instance:
val words1 = "This is an example sentence about a lazy dog".split(" ")
val words2 = "The quick brown fox jumps over the lazy dog".split(" ")
for (
i <- words1;
j <- words2 if i.equals(j)
) yield i
res22: Array[String] = Array(lazy, dog)
It's worth noting that you can also use a numeric range:
You can also use a numeric range:
for (i <- 0 to 5) yield i
res11: scala.collection.immutable.IndexedSeq[Int] =
Vector(0, 1, 2, 3, 4, 5)