如何模式匹配具有多个参数列表的类? [英] How to pattern match a class with multiple argument lists?

查看:283
本文介绍了如何模式匹配具有多个参数列表的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个类:

  class DateTime(year:Int,month:Int,day:Int) ,分钟:Int,秒:Int)

unapply 方法看起来像,如果我想匹配如下:

  dt match {
case DateTime(2012,12,12)(12,_,_)=> // 2012年12月12日12点
/ * ... * /
}

我试过这个:

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


$ b

但是这没有真正起作用。

解决方案

case类匹配(并做其他漂亮的东西)第一组参数:

  scala> case class A(i:Int)(j:Int){} 
定义类A

scala> A(5)(4)匹配{情况A(5)=> Hi}
res14:java.lang.String = Hi

scala> A(5)(4)== A(5)(9)
res15:Boolean = true


$ b b

如果它不是一个case类,你可以定义unapply是任何你想要的,所以它真的取决于类的实现。默认情况下,没有取消应用,因此只能匹配类型。



如果你想使用nifty case类的功能,包括能够匹配和做平等在一切,但有某种分裂,你可以嵌套病例类:

 病例类时间(小时: int,second:Int){} 
case类日期(年份:Int,月份: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


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.

解决方案

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

这篇关于如何模式匹配具有多个参数列表的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆