3

在为 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)

导致输出:

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)

这完全让我困惑。如果对于一个给定的输入isDefinedAt组成的两个偏函数返回true,我希望我也可以将apply它返回到相同的输入。

4

1 回答 1

5

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

val testPf1: PartialFunction[Any, Boolean] = { case 2 ⇒ true }
val testPf2: PartialFunction[Any, Boolean] = { case 1 ⇒ true }

使组合按预期工作。

的原因MatchError

PartialFunction[Any, Boolean]{ case 2 => true } 

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

使语句扩展为

 PartialFunction.apply[Any, Boolean](_ match { case 2 => true })

然后转换为

{ case x => f(x) }

当然,它总是会在不匹配的输入上返回trueisDefined抛出 MatchError f

于 2015-10-01T13:54:11.207 回答