是否可以使用Scala中的模式匹配系统进行比较匹配?例如:
a match {
case 10 => println("ten")
case _ > 10 => println("greater than ten")
case _ => println("less than ten")
}
第二个case语句是非法的,但我希望能够指定“当a大于”。
发布于 2022-02-26 16:58:03
Scala的模式匹配允许您定义自己的提取器。在这种情况下,您可以简单地定义一个新的提取器:
class GreaterThan(n: Int) {
def unapply(i: Int) = i > n
}
val GreaterThan10 = GreaterThan(10)
a match {
case 10 => ???
case GreaterThan10() => ???
case _ => ???
}
或者只使用模式保护。
https://stackoverflow.com/questions/1585395
复制相似问题