开发者

How to pattern match a class with multiple argument lists?

开发者 https://www.devze.com 2023-03-08 17:15 出处:网络
Consider this class: class DateTime(year: Int, month: Int, day: Int)(hour: Int, minute: Int, second: Int)

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) = 
  S开发者_开发技巧ome((dt.year, dt.month, dt.day),(dt.hour, dt.minute, dt.second))

But that didn't really work.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消