代码在这里:
abstract class Element { def contents: Array[String] val height = contents.length val width = if(height ==0 ) 0 else contents(0).length override def toString = contents(0) } class ArrayElement(override val contents: Array[String]) extends Element class LineElementT(s: String) extends Element { override def contents = Array(s) } class LineElementF(s: String) extends Element { override val contents = Array(s) }
除了LineElementF之外,这三个子类都可以,LineElementF在使用val lef = new LineElementF(“Wrong”)创建实例时抛出NullPointerException
解决方法
这个NPE发生在高度初始化时.在高度初始化时,LineElementF的val内容未初始化.
您可以通过将高度和宽度都声明为惰性来避免此NPE:
lazy val height = contents.length lazy val width = if(height ==0 ) 0 else contents(0).length