How does orElse work on PartialFunctions

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I am getting very bizarre behavior (at least it seems to me) with the orElse method defined on PartialFunction

It would seem to me that:

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

makes sense but this is not how it is behaving and I am having a lot of trouble understanding why as the types signatures seem to indicate what I exposed above.

Here is a transcript of what I am observing with 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] =   scala> a("hello") Bye  scala> a("bye") scala.MatchError: bye (of class java.lang.String)   at $anonfun$1.apply(:7)   at $anonfun$1.apply(:7)   at scala.PartialFunction$$anonfun$apply$1.applyOrElse(PartialFunction.scala:242)   at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)   ... 33 elided  scala> val b = a.orElse(PartialFunction.empty[Any, Unit]) b: PartialFunction[String,Unit] =   scala> b("sdf") scala.MatchError: sdf (of class java.lang.String)   at $anonfun$1.apply(:7)   at $anonfun$1.apply(:7)   at scala.PartialFunction$$anonfun$apply$1.applyOrElse(PartialFunction.scala:242)   at scala.PartialFunction$OrElse.apply(PartialFunction.scala:162)   ... 33 elided

Note the return type of val b which has not widen the type of the PartialFunction.

But this also does not work as expected:

scala> val c = a.orElse(PartialFunction.empty[String, Unit]) c: PartialFunction[String,Unit] =   scala> c("sdfsdf") scala.MatchError: sdfsdf (of class java.lang.String)   at $anonfun$1.apply(:7)   at $anonfun$1.apply(:7)   at scala.PartialFunction$$anonfun$apply$1.applyOrElse(PartialFunction.scala:242)   at scala.PartialFunction$OrElse.apply(PartialFunction.scala:162)   ... 33 elided
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!