Collection view vs withFilter

Viewed 179

Both views and withFilter solve the problem of intermediate collection creations. What's the difference between them ?

List("a", "b", "c").withFilter(_ == "b").withFilter(_ == "c").map(x => x)

vs

 List("a", "b", "c").view.filter(_ == "b").filter(_ == "c").map(x => x)
2 Answers
List("a", "b", "c").withFilter(_ == "b").withFilter(_ == "c").map(x => x)

Result:

 List[String] = List()

Note: the result is no longer lazy.

List("a", "b", "c").view.filter(_ == "b").filter(_ == "c").map(x => x)

Result:

scala.collection.SeqView[String,Seq[_]] = SeqViewFFM(...)

The result has not been evaluated, it is still a view.

The first is lazy until you call the map, while the second one is just lazy (not executed). For the second one it will finally execute when decide to call force - which you have not done in your example. So it'd look like:

List("a", "b", "c").view.filter(_ == "b").filter(_ == "c").map(x => x).force

this is equivalent to the first one.

See here and here about withFilter and view in Scala.

Related