4

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)
EugeneMi
  • 3,475
  • 3
  • 38
  • 57

2 Answers2

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

Terry Dactyl
  • 1,839
  • 12
  • 21
2

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.

Tanjin
  • 2,442
  • 1
  • 13
  • 20