Gary Sieling

Scala list comprehension

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  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 

It's worth noting that you can also use a numeric range:
You can also use a numeric range:

for (i 
	
Exit mobile version