这很奇怪,但我的代码打印u。你知道它为什么会做这种事吗?
object PF extends App {
val f1: PartialFunction[Int, String] = {
case x: Int if x % 2 == 0 => "2"
}
val f2: PartialFunction[Int, String] = {
case x: Int if x % 3 == 0 => "3"
}
val f3: PartialFunction[Int, String] = {
case x: Int if x % 5 == 0 => "5"
}
val result = f1.orElse(f2.orElse(f3.orElse("<undef>")))
println(result.apply(1))
}发布于 2015-12-16 12:28:25
您的代码将字符串"“解释为PartialFunction
val result: PartialFunction[Int, String] = "<undef>"
result.apply(1) // second character of "<undef>" --> u这通过从String到WrappedString的隐式转换来实现,这是Seq[Char]的一个子类型。此外,Seq[T]是PartialFunction[Int, T]的一个子类型(给定索引,如果存在Seq元素,则获取它)。
最后一行到达这种情况,因为1不能被2,3,5中的任何一个整除(因此它通过f1、f2和f3)。
你想要的是applyOrElse
val fun = f1 orElse f2 orElse f3
fun.applyOrElse(1, "<undef>") // --> "<undef>"或者,您可以指定回退部分函数:
val result = f1 orElse f2 orElse f3 orElse {
case _ => "<undef>"
}https://stackoverflow.com/questions/34311923
复制相似问题