我刚刚遇到另一个模式匹配错误。
谷歌找到了很多。并且这个 google 请求应该首先在任何 akka 文档中链接,以向用户提供有关 scala 中基于消息的编程困难的公平信息。
有些错误已解决,有些则没有。它们是通用的,不同的代码可以应用于一个错误。
我有一件在 2.9.2 中仍然停止工作,我想知道错误状态。所以我需要熟悉 scala 错误数据库的人的帮助,他们可以指出与我的代码对应的错误。
示例代码:
object Test {
sealed trait Pattern[T] {
val data : T
}
object Pattern {
def apply[T](data : T) : Pattern[T] = Primary(data)
def apply[T](data : T, f : Float) : Pattern[T] = Full(data,f)
def unapply[T](pat : Pattern[T]) : Option[T] = Some(pat.data)
}
final case class Primary[T](data : T) extends Pattern[T]
final case class Full[T](data : T, f: Float) extends Pattern[T]
val recognize1 : PartialFunction[Pattern[Any],Unit] = {
case pat@Pattern(d) => println("pattern recognized: " + pat)
case _ => println("simple failed")
}
val recognize2 : PartialFunction[Pattern[Any],Unit] = {
case pat@Full(x : Int, f) => println("full@Int detected: " + pat)
case pat@Pattern(c : Float) => println("pat@Float detected: " + pat)
case _ => println("full-pattern detection failed")
}
val recognize3 : PartialFunction[Pattern[Any],Unit] = {
case pat@Pattern(x : Int) => println("pat@Int detected: " + pat)
case pat@Pattern(c : Float) => println("pat@Float detected: " + pat)
case _ => println("pattern-pattern detection failed")
}
val recognize4 : PartialFunction[Pattern[Any],Unit] = {
case pat@Full(x : Int, f) => println("full@Int detected: " + pat)
case pat@Full(c : Float, f) => println("full@Float detected: " + pat)
case _ => println("full-full detection failed")
}
val allRecognize : List[PartialFunction[Pattern[Any],Unit]] =
List( recognize1, recognize2, recognize3, recognize4)
val tests : List[Any] = List(3) ++ List(5.0f)
def testAll() = for (t <- tests) {
println("test: " + t)
val primary = Pattern(t)
for (r <- allRecognize) r(primary)
val full = Pattern(t,1.0f)
for (r <- allRecognize) r(full)
println("")
}
}
和相应的输出:
scala> Test.testAll()
test: 3
pattern recognized: Primary(3)
full-pattern detection failed
pat@Int detected: Primary(3)
full-full detection failed
pattern recognized: Full(3,1.0)
full@Int detected: Full(3,1.0)
pat@Int detected: Full(3,1.0)
full@Int detected: Full(3,1.0)
test: 5.0
pattern recognized: Primary(5.0)
pat@Float detected: Primary(5.0)
pat@Float detected: Primary(5.0)
full-full detection failed
pattern recognized: Full(5.0,1.0)
full-pattern detection failed
pat@Float detected: Full(5.0,1.0)
full@Float detected: Full(5.0,1.0)
测试 Int 效果很好,因为首先匹配 Int。
匹配浮点数会出现问题。当我对 Int 和 Float(模式或完整)使用相同的提取器时,一切正常。但是当我混合提取器并尝试将 Int 与 Full 提取并尝试 Float 与 Pattern 时,一切都出错了。
主要问题:它是什么错误(你真的应该知道 scala 内部来解决它)?
较小的问题:对此最优雅的解决方法是什么?
模式特征被写成 (U,Option[V])