我定义了一个自定义提取器来获取列表的最后一个元素,如 https://stackoverflow.com/a/6697749/1092910 :
object :+ {
def unapply[A](l: List[A]): Option[(List[A], A)] = {
if (l.isEmpty)
None
else
Some(l.init, l.last)
}
}
现在这匹配“好”:
List(1, 2, 3) match {
case init :+ last => "good"
case head :: tail => "bad"
}
但是如果我添加另一个子句,它现在突然匹配“坏”:
List(1, 2, 3) match {
case List(7) => "never"
case init :+ last => "good"
case head :: tail => "bad"
}
这种行为的原因是什么?
最佳答案
它是 #1697/2337 和十几个副本。
https://issues.scala-lang.org/browse/SI-1697
可以肯定地说,它不会以直接方式修复,而是通过删除 virtpatmat 实现的模式匹配器来修复。尝试最近的构建并使用 -Yvirtpatmat 进行编译,您将得到正确的答案。
关于scala - 使用提取器匹配订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8469139/