我认为这段代码应该不起作用,但它确实有效(在 Scala 2.10 中):
scala> ((i: Int) => i.toString match {
| case s if s.length == 2 => "A two digit number"
| case s if s.length == 3 => "A three digit number"
| }): PartialFunction[Int,String]
res0: PartialFunction[Int,String] = <function1>
// other interactions omitted
scala> res0.orElse(PartialFunction((i: Int) => i.toString))
res5: PartialFunction[Int,String] = <function1>
scala> res5(1)
res6: String = 1
它是如何工作的?我希望有一个MatchError
被扔进去res0
.
Scala 语言规范似乎没有明确记录如何res0
应该被解释。
诀窍在于,编译器不会将您的定义解释为转换为部分函数的总函数——它实际上首先创建了一个部分函数。您可以通过注意来验证res0.isDefinedAt(1) == false
.
如果您实际上将总函数转换为部分函数,您将得到您期望的行为:
scala> PartialFunction((i: Int) => i.toString match {
| case s if s.length == 2 => "A two digit number"
| case s if s.length == 3 => "A three digit number"
| })
res0: PartialFunction[Int,String] = <function1>
scala> res0 orElse ({ case i => i.toString }: PartialFunction[Int, String])
res1: PartialFunction[Int,String] = <function1>
scala> res1(1)
scala.MatchError: 1 (of class java.lang.String)
// ...
在这个例子中,PartialFunction.apply
将其参数视为一个总函数,因此有关其定义位置的任何信息都会丢失。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)