Why does implement abstract method using val and call from superclass in val expression return NullPointerException

假如想象 提交于 2019-11-29 17:30:27

Here is what your code attempts to do when it initializes MainFoo:

  1. Allocate a block of memory, with enough space for val calcNumbers and val numbers, initially set to 0.
  2. Run the initializer of the base class Foo, where it attempts to invoke numbers.map while initializing calcNumbers.
  3. Run the initializer of the child class MainFoo, where it initializes numbers to List(1, 2, 3).

Since numbers is not initialized yet when you try to access it in val calcNumbers = ..., you get a NullPointerException.

Possible workarounds:

  1. Make numbers in MainFoo a def
  2. Make numbers in MainFoo a lazy val
  3. Make calcNumbers in Foo a def
  4. Make calcNumbers in Foo a lazy val

Every workaround prevents that an eager value initialization invokes numbers.map on a non-initialized value numbers.

The FAQ offers a few other solutions, and it also mentions the (costly) compiler flag -Xcheckinit.


You might also find these related answers useful:

  1. Scala overridden value: parent code is run but value is not assigned at parent.

  2. Assertion with require in abstract superclass creates NPE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!