case class MyCaseClass(x: Int) // some case clas with an Int parameter
val x0 = 17 // some given Int value
val a = MyCaseClass(x=18) // a case class object
// using pattern matching to find out if *a* is of type MyCaseClass and its parameter x equals x0+1
a match {
case MyCaseClass(x) if x == x0+1 => println("Found my case class with x==x0+1")
}
如果语句if x == x0+1
可以跳过上面的内容并只写]会很好,>
case MyCaseClass(x0+1) => println("Found my case class with x==x0+1")
不幸的是,这不能编译-但是有某种方法可以实现这样的效果吗?
假设以下情况案例类MyCaseClass(x:Int)//一些带有Int参数的案例分类val x0 = 17 //一些给定的Int值val a = MyCaseClass(x = 18)//一个案例类对象// ...
好吧,只要case MyCaseClass(18)
,或者如果您确实需要算术,则可以:
如果定义提取器对象,则可以完成此工作