EugeneMi
EugeneMi

Reputation: 3575

Collection view vs withFilter

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)

Upvotes: 4

Views: 255

Answers (2)

Tanjin
Tanjin

Reputation: 2452

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.

Upvotes: 2

Terry Dactyl
Terry Dactyl

Reputation: 1868

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.

Upvotes: 2

Related Questions