我正在阅读 Martin Odersky 的《Scala 编程》(第二版)一书,我对第 10 章中的示例有疑问。
这是我几乎在本章末尾的文件:
class Element
object Element {
private class ArrayElement(
val contents: Array[String]
) extends Element
private class LineElement(s: String) extends ArrayElement(Array(s)) {
override def width = s.length
override def height = 1
}
private 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)
}
def elem(contents: Array[String]): Element =
new ArrayElement(contents)
def elem(chr: Char, width: Int, height: Int): Element =
new UniformElement(chr, width, height)
def elem(line: String): Element =
new LineElement(line)
}
abstract class Element {
def contents: Array[String]
def width: Int =
if (height == 0) 0 else contents(0).length
def height: Int = contents.length
def above(that: Element): Element =
elem(this.contents ++ that.contents)
def beside(that: Element): Element =
elem(
for (
(line1, line2) <- this.contents zip that.contents
) yield line1 + line2
)
}
编译器这样说:
defined class Element
<console>:15: error: method width overrides nothing
override def width = s.length
^
<console>:16: error: method height overrides nothing
override def height = 1
^
<console>:21: error: value width overrides nothing
override val width: Int,
^
<console>:22: error: value height overrides nothing
override val height: Int
^
<console>:17: error: not found: value elem
elem(this.contents ++ that.contents)
^
<console>:20: error: not found: value elem
elem(
^
如果我class Element
从一开始就删除了,那么当我尝试对其进行子类化时,它会抱怨找不到 Element 类型。
我在这里找到了几个主题,这些主题已经在讨论本书中的这一章,但我无法使用那里提出的任何解决方案。
我错过了什么?
问候,诺伯特