问题描述
我正在研究在Scala中编程",它说您可以用字段覆盖无参数方法,广告给出了以下示例:
I am working through "Programming in Scala" and it says that you can override a parameterless method with a field, ad gives the following example:
abstract class Element {
def contents: Array[String]
val height: Int = contents.length
val width: Int = if (height == 0) 0 else contents(0).length
}
class ArrayElement(conts: Array[String]) extends Element {
val contents:Array[String] = conts
}
val a = Array("Hello", "mom")
println(a(0))
val x = new ArrayElement(a)
println(x.contents)
println("Hello, " + x.height)
但是此代码为我生成了一个空指针异常.用"def内容:"替换"val内容:"可以正常工作.如果内容数组确实正确传递,我真的无法理解空指针异常的来源.它似乎来自"val height = contents.length"行,因为用"def height"替换它们也可以正常运行.我对这个示例不了解什么?
However this code produces a null pointer exception for me. Replacing "val contents:" with "def contents:" works fine. I can't really understand where the null pointer exception is coming from, if the contents array is indeed being correctly passed. It seems to be coming from the "val height = contents.length" line, because replacing those with "def height" also runs correctly. What am I not understanding about this example?
推荐答案
这与抽象类中的评估顺序有关.
This is about evaluation order in your abstract class.
val
在初始化时评估一次,而def
在每次访问时评估. NullPointerException发生在初始化期间,因为height
在尚未初始化时访问contents
.
val
s are evaluated once at initialization time, whereas def
s are evaluated every time they are accessed. The NullPointerException happens during initialization time, because height
accesses contents
at a time when it hasn't been initialized yet.
正如您建议的那样,将height
和width
转换为def
s是防止该问题的一种方法.
As you suggest, turning height
and width
into def
s is one way to prevent the problem.
这篇关于用字段覆盖无参数方法时的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!