在抽象构造函数中访问覆盖的 val 时出现 NullPointerException [英] NullPointerException when accessing overriden val in abstract constructor
本文介绍了在抽象构造函数中访问覆盖的 val 时出现 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下(简化的)示例:
Consider the following (simplified) example:
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
放在具体类中:
However, if we put chained
in the concrete class:
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 上.)
I have to admit I have absolutely no idea what is happening here. Bug? (This is on Scala 2.8.1.)
推荐答案
"为什么我的抽象或重写 val 为空?"https://github.com/paulp/scala-faq/wiki/Initialization-Order
"Why is my abstract or overriden val null?" https://github.com/paulp/scala-faq/wiki/Initialization-Order
这篇关于在抽象构造函数中访问覆盖的 val 时出现 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文