相关疑难解决方法(0)

orElse如何处理PartialFunctions

我使用orElse定义的方法得到了非常奇怪的行为(至少在我看来)PartialFunction

在我看来:

val a = PartialFunction[String, Unit] {
    case "hello" => println("Bye")
}
val b: PartialFunction[Any, Unit] = a.orElse(PartialFunction.empty[Any, Unit])
a("hello") // "Bye"
a("bogus") // MatchError
b("bogus") // Nothing
b(true)    // Nothing
Run Code Online (Sandbox Code Playgroud)

有道理,但这不是它的表现方式,我很难理解为什么类型签名似乎表明我在上面暴露了什么.

以下是我使用Scala 2.11.2观察的内容的记录:

Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val a = PartialFunction[String, Unit] {
     | case "hello" => println("Bye")
     | }
a: PartialFunction[String,Unit] = <function1> …
Run Code Online (Sandbox Code Playgroud)

functional-programming scala partialfunction read-eval-print-loop

9
推荐指数
1
解决办法
8677
查看次数