Follow-up on Scala: Filter a List with an Extractor

635x282xscala.gif.pagespeed.ic.uwF00NWKP7To recap: In Scala: Filter a List with an Extractor, I could not get some list syntax using an extractor to be as nice as the syntax of a for comprehension.

List syntax with extractor:

someMembers filter { _ match { case Member(n) => true case _ => false } }

vs. for comprehension syntax with extractor:

for(Member(n) <- someMembers) yield n

As I get more familiar with Scala, I'm no longer surprised when I find out that there actually is an elegant solution for what I want to do. (I just wish it were easier to find.) In this case, the "collect" function is what I wanted:

someMembers collect { case Member(n) => n }

This can also be used to create a list with any of a set of items. For example, let's say you want "Member" and "TrialUser" types collected in your result:

someMembers collect { case Member(m) => m case TrialUser(t) => t }

The best thing about "collect" is that it ignores any items in the list it comes across which do not match any of the provided cases. This is not so with the "map" keyword, which throws a MatchError when a case is encountered that does not map to one of the cases.

It's important to know that distinction because depending on the case, you may want to use "map" instead of collect and thereby insure that nothing is in the List without your knowledge. If you don't care, though, or you are purposefully throwing some items away, "collect" is your function!

One thought on “Follow-up on Scala: Filter a List with an Extractor

Leave a Reply

Your email address will not be published. Required fields are marked *