Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match a class with multiple argument lists?

Consider this class:

class DateTime(year: Int, month: Int, day: Int)(hour: Int, minute: Int, second: Int)

how would the unapply method look like, if I would like to match against something like:

dt match {
  case DateTime(2012, 12, 12)(12, _, _) => // December 12th 2012, 12 o'clock
  /* ... */
}

I tried this:

def unapply(dt: DateTime) = 
  Some((dt.year, dt.month, dt.day),(dt.hour, dt.minute, dt.second))

But that didn't really work.

like image 972
soc Avatar asked May 27 '11 19:05

soc


3 Answers

Case classes match (and do their other nifty things) only on the first set of parameters:

scala> case class A(i: Int)(j: Int) { } defined class A  scala> A(5)(4) match { case A(5) => "Hi" } res14: java.lang.String = Hi  scala> A(5)(4) == A(5)(9) res15: Boolean = true 

If it's not a case class, you can define the unapply to be anything you want, so it's really up to the implementer of the class. By default, there is no unapply, so you can match only on the type.

If you want to use the nifty case class features including being able to match and do equality on everything, but have some sort of division, you could nest case classes:

case class Time(hour: Int, minute: Int, second: Int) { } case class Date(year: Int, month: Int, day: Int) { } case class DateTime(date: Date, time: Time) { }  scala> val dt = DateTime(Date(2011,5,27), Time(15,21,50)) scala> dt match { case DateTime(Date(2011,_,_),Time(h,m,50)) => println(h + ":" + m) } 15:21 
like image 121
Rex Kerr Avatar answered Sep 23 '22 15:09

Rex Kerr


Just to build on Rex's answer, not only can you only pattern match on the first parameter block, but this behaviour is very much by design.

The more interesting question is why case classes, as algebraic data types, even support multiple parameter lists...

There's no strong enough justification to add special behaviour for case classes, and multiple parameter lists turn out to be pretty useful. In production code this facility is often only used to supply implicit arguments, which you quite naturally wouldn't want to pattern match.

like image 40
Kevin Wright Avatar answered Sep 21 '22 15:09

Kevin Wright


It probably didn't work because Scala has no comma operator, and you're returning Some((a,b),(x,y)) from the extractor. If you used Some(((a,b,c),(x,y,z))) instead (i.e. a Tuple2[Tuple3[A,B,C],Tuple3[X,Y,Z]] I think it would probably work.

like image 42
Alex Cruise Avatar answered Sep 20 '22 15:09

Alex Cruise