3

アクターの 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)

それは私を完全に混乱させました。isDefinedAt2 つの部分関数の構成に関する特定の入力に対してが返される場合、同じ入力に対してtrueもそれが可能であると期待できます。apply

4

1 に答える 1

5

したがって、最初の 2 行を次のように変更することを学びました。

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

構成を期待どおりに機能させます。

その理由MatchError

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

私は実際にaを aPartialFunction.applyに変換するを呼び出しているようです。Function1PartialFunction

ステートメントが展開されるように

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

その後、に変換されます

{ case x => f(x) }

もちろん、これは常にtrueforを返し、isDefinedと一致しない入力に対して MatchError をスローしfます。

于 2015-10-01T13:54:11.207 に答える