Quickfix to Expand Case-Class Bindings in Pattern Matching
When writing Scala code that involves pattern matching I often work with (nested) case classes and sequences of case classes. I usually start with a simple binding like this
case class Person(firstName: String, lastName: String) List(Person("Mirko", "Stocker")) match { case person :: Nil =>; ... }
and then when I need to access members of the matched class convert it to use the extractor:
List(Person("Mirko", "Stocker")) match { case Person(firstName, lastName) :: Nil => ... }
What’s tedious about that step is that one needs to know how many arguments there are and name all the bindings. But not for much longer! I wrote a quick-fix for the Scala IDE that does this for you:
Ctrl+1 brings up the available quick fixes:
And this is what happens when the binding you’re expanding is used in the pattern’s body:
It also works if you use a typed pattern where the type is a case class:
This feature isn’t in the recently released Milestone 1, but it should be part of the next one (or one of the upcoming nightly builds). Suggestions for a better wording – expand case class binding – are welcome 🙂