考虑以下(简化的)示例:
abstract class Bar[T] {
val f: PartialFunction[T, T]
val default: PartialFunction[T, T] = { case x => x }
val chained = f orElse default
}
class Foo extends Bar[Int] {
val f: PartialFunction[Int, Int] = { case 1 => 2 }
}
并观察它崩溃:
scala> val foo = new Foo
java.lang.NullPointerException
at Bar.<init>(<console>:8)
at Foo.<init>(<console>:6)
at .<init>(<console>:7)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:9)
at RequestResult$.<clinit>(<console>)
at RequestResult$scala_repl_result(<console>)
....
但是,如果我们把chained
在具体类中:
abstract class Bar[T] {
val f: PartialFunction[T, T]
val default: PartialFunction[T, T] = { case x => x }
}
class Foo extends Bar[Int] {
val f: PartialFunction[Int, Int] = { case 1 => 2 }
val chained = f orElse default
}
它按预期工作:
scala> val foo = new Foo
foo: Foo = Foo@16132c4
我必须承认我完全不知道这里发生了什么。漏洞? (这是在 Scala 2.8.1 上。)
“为什么我的抽象或重写 val 为空?”https://github.com/paulp/scala-faq/wiki/Initialization-Order https://github.com/paulp/scala-faq/wiki/Initialization-Order
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)