The Coding Journal ツ

Home

Impressum

x3ro’s Toolkit

TLDR: Take my directly to the solution.

I found this nice trick on the Scala forums . Lets imagine we have a case class such as the following:

This case class, as you probably know, can now be “pattern matched” like this:

But what if, most of the time, you only need the first two arguments, and the others are mostly irrelevant for your pattern matching. You wouldn’t want to write Foo(a, _, _ ,_) all the time, right? One possibility would be to write the unapply(x:Foo) method yourself:

But what if you would like to use both unapply methods at some point? In that case you have to define multiple objects with different unapply methods, because unfortunately, unlike apply , unapply can’t be overloaded (because it always takes the the same argument).

So here is my approach to multiple unapply methods:

While it isn’t exactly awesome because you have to introduce a new object Foo_ , I like it better than always having to write out all 4 (or more) parameters.

If you have a better approach to this problem, please let me know :)

TLDR: Take my directly to the solution. I found this nice trick on the Scala forums. Lets imagine we have a case class such as the following: case class Foo(a:String,...

Nicolas Marchildon on April 20, 2013 at 3:34 am said: Instead of using a meaningless underscore to differenciate them, I suggest you name it SimpleFoo, ShortFoo, or KungFu – as long as it makes sense! Reply ↓ Lucas Jenß on April 20, 2013 at 10:46 am said: I certainly agree that a meaningless underscore is not the way to go! Also, lol for KungFu :) Reply ↓

Instead of using a meaningless underscore to differenciate them, I suggest you name it SimpleFoo, ShortFoo, or KungFu – as long as it makes sense!

Lucas Jenß on April 20, 2013 at 10:46 am said: I certainly agree that a meaningless underscore is not the way to go! Also, lol for KungFu :) Reply ↓

I certainly agree that a meaningless underscore is not the way to go! Also, lol for KungFu :)

Jiunjiun Ma on August 28, 2013 at 7:49 pm said: Another way to solve it is to implement the unapplySeq() method, so you can match a variable argument list. With unapply(), it may meet most of the matching needs. Reply ↓

Another way to solve it is to implement the unapplySeq() method, so you can match a variable argument list. With unapply(), it may meet most of the matching needs.

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

Name *

Email *

Website

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>