Scala:是否可以将类似(x + 1)的术语用作案例类模式匹配的参数?

问题描述 投票:0回答:2

假设以下情况

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)//一个案例类对象// ...

scala pattern-matching parameter-passing case-class
2个回答
1
投票

好吧,只要case MyCaseClass(18),或者如果您确实需要算术,则可以:


1
投票

如果定义提取器对象,则可以完成此工作

© www.soinside.com 2019 - 2024. All rights reserved.