PartialFunctions组合的MatchError与orElse

Sas*_*erg 3 scala partialfunction

在为Actor编写Specs2规范时,我MatchError对一些部分函数的组合感到有点困惑.

一个最小的例子:

val testPf1 = PartialFunction[Any, Boolean]{ case 2 ? true }
val testPf2 = PartialFunction[Any, Boolean]{ case 1 ? true }
val testPf = testPf1 orElse testPf2
testPf.isDefinedAt(1)
testPf.isDefinedAt(2)
testPf(1)
testPf(2)
Run Code Online (Sandbox Code Playgroud)

导致输出:

testPf1: PartialFunction[Any,Boolean] = <function1>
testPf2: PartialFunction[Any,Boolean] = <function1>
testPf: PartialFunction[Any,Boolean] = <function1>
res0: Boolean = true
res1: Boolean = true
scala.MatchError: 1 (of class java.lang.Integer)
    at com.dasgip.controller.common.informationmodel.programming.parametersequence.A$A161$A$A161$$anonfun$testPf1$1.apply(PFTest.sc0.tmp:33)
    at com.dasgip.controller.common.informationmodel.programming.parametersequence.A$A161$A$A161$$anonfun$testPf1$1.apply(PFTest.sc0.tmp:33)
    at scala.PartialFunction$$anonfun$apply$1.applyOrElse(PFTest.sc0.tmp:243)
    at scala.PartialFunction$OrElse.apply(PFTest.sc0.tmp:163)
    at #worksheet#.#worksheet#(PFTest.sc0.tmp:36)
Run Code Online (Sandbox Code Playgroud)

那让我很困惑.如果对于给定输入isDefinedAt的两个部分函数的组合返回true,我希望我也可以将apply它输出到同一个.

Sas*_*erg 5

因此,我了解到将前两行更改为:

val testPf1: PartialFunction[Any, Boolean] = { case 2 ? true }
val testPf2: PartialFunction[Any, Boolean] = { case 1 ? true }
Run Code Online (Sandbox Code Playgroud)

使组合按预期工作.

原因MatchError就在于

PartialFunction[Any, Boolean]{ case 2 => true } 
Run Code Online (Sandbox Code Playgroud)

我实际上似乎在调用PartialFunction.apply,它将a转换Function1为a PartialFunction.

因此声明扩展到

 PartialFunction.apply[Any, Boolean](_ match { case 2 => true })
Run Code Online (Sandbox Code Playgroud)

然后转换为

{ case x => f(x) }
Run Code Online (Sandbox Code Playgroud)

其中,当然,总是返回trueisDefined,扔在不匹配的输入MatchError f.