Page 232 (PDF page 270):
Based on the superclass:
//from page: 222
abstract class Element {
def contents: Array[String]
val height = contents.length
val width = if (height == 0) 0 else contents(0).length
}
The book goes on to extend with another sub-class:
class UniformElement(
ch: Char,
override val width: Int,
override val height: Int
) extends Element {
private val line = ch.toString * width
def contents = Array.fill(height)(line)
}
This causes a null-pointer exception in the Scala REPL.
I found that others also get trapped on this, possibly from older
versions of the book:
-
https://stackoverflow.com/questions/42312232/npe-in-using-scala-array-fill
/42312929
-
https://html.developreference.com/article/22372654/Scala+companion+object+
with+abstract+class
----
I added a footnote that clarifies which version of Element UniformElement
should extend, which is the one in Listing 10.2. If you do that, the NPE
doesn't happen.
|
Page 251 (PDF page 289):
Listing 10.6 - Invoking a superclass constructor.
it should revise to:
class LineElement(s: String) extends ArrayElement(Array(s)) {
override val width = s.length
override val height = 1
}
,not :
class LineElement(s: String) extends ArrayElement(Array(s)) {
override def width = s.length
override def height = 1
}
,otherwise it would report like this:
On line 2: error: stable, immutable value required to override:
val width: Int (defined in class Element)
override def height = 1
^
On line 3: error: stable, immutable value required to override:
val height: Int (defined in class Element)
-----
The issue is from extending the wrong version of Element. I added
comments to clarify in 5ed. Tnx.
|