子类不扩展抽象类

时间:2013-11-30 12:59:35

标签: scala read-eval-print-loop

我正在通过“Scala编程”并继续使用这些示例。我似乎被困在第10章,我们从抽象类中创建子类。

我无法弄清楚为什么我的代码无法编译;似乎ArrayElement应该自动成为一种Element?

代码:

abstract class Element {
    def contents: Array[String]
    def height: Int = contents.length
    def width: Int = if (height == 0) 0 else contents(0).length
    def above(that: Element): Element =
        new ArrayElement(this.contents ++ that.contents)
    def beside(that: Element): Element =
        new ArrayElement(
            for (
                (line1, line2) <- this.contents zip that.contents
            ) yield line1 + line2
        )
    override def toString: String = contents mkString "\n"
}

class ArrayElement(
    val contents: Array[String]
) extends Element

错误:

<console>:16: error: type mismatch;
 found   : ArrayElement
 required: Element
               new ArrayElement(this.contents ++ that.contents)
               ^
<console>:18: error: type mismatch;
 found   : ArrayElement
 required: Element
               new ArrayElement(
               ^

谢谢!

1 个答案:

答案 0 :(得分:1)

这应该有效。看起来你正在使用REPL。

由于两个类之间存在递归依赖关系,因此在通常输入REPL 时无效。您需要使用:粘贴模式,如下所示:

:paste

abstract class Element {
    def contents: Array[String]
    def height: Int = contents.length
    def width: Int = if (height == 0) 0 else contents(0).length
    def above(that: Element): Element =
        new ArrayElement(this.contents ++ that.contents)
    def beside(that: Element): Element =
        new ArrayElement(
            for (
                (line1, line2) <- this.contents zip that.contents
            ) yield line1 + line2
        )
    override def toString: String = contents mkString "\n"
}

class ArrayElement(
    val contents: Array[String]
) extends Element

然后同时按下Ctrl和D键。