How to pattern match a class with multiple argument lists?

北战南征 提交于 2019-12-08 14:37:59

问题


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.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6156656/how-to-pattern-match-a-class-with-multiple-argument-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!