Scala: Filter a list with an extractor

scala-logo-croped

An “extractor” in Scala is a technique utilizing some syntactic sugar to simplify pattern matching against an object when you want to then do something additional with the object like “extract” a property from it. Look at this tutorial on Scala-Lang.org if you aren’t familiar.

But how do you use them with common List methods?

I found that quite a bit of Googling around wouldn’t produce the answer, so I did some experimentation and found that it is a bit klunky. As you can see in the gist at the bottom of this post, it seems that you have to supply a partially-applied function with the full pattern match. For a list named “someMembers” you do this to get a new list matching :

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

This is not nearly as nice as the for-comprehension approach:

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

Try the below in your REPL with paste mode (":paste") and let me know what you think.

Update:
In this follow-up post, I resolve the issue!

Leave a Reply

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