Reputation: 47061
I got the FilterMonadic
from the following line:
val f = ((2 to 10) withFilter (_ > 5) withFilter( _ < 8))
However, I found f
doesn't have a toList
method. Does anyone have ideas about how to convert it into a List?
And what are the main different between withFilter
and filter
method?
Upvotes: 1
Views: 602
Reputation: 14224
The easiest way is probably f.map(identity)
, which doesn't necessarily return a List
, but an appropriate type of sequence, based on the original sequence type before filtering.
If you want strictly a List
, convert the result to List
afterwards: f.map(identity).toList
.
As for the difference, for most collections filter
immediately performs the filtering, builds a new collection in memory and returns it, and withFilter
returns an object, which stores the original collection and does the filtering only when an element is requested.
Upvotes: 2
Reputation: 8487
You can use flatMap
:
scala> val f = ((2 to 10) withFilter (_ > 5) withFilter( _ < 8))
f: scala.collection.generic.FilterMonadic[Int,scala.collection.immutable.IndexedSeq[Int]] = scala.collection.TraversableLike$WithFilter@60b8da0
scala> f.flatMap(List(_)).toList
res0: List[Int] = List(6, 7)
Upvotes: 0