Frage

I'm making my way through "Programming in Scala" and going along with the examples. I seem to be stuck on Chapter 10 where we make subclasses from an abstract class.

I can't figure out why my code won't compile; it seems like ArrayElement should automatically be a type of Element?

Code:

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

Error:

<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(
               ^

Thanks!

War es hilfreich?

Lösung

This should work. It looks like you are using the REPL, though.

This won't work when typed in to the REPL normally because of a recursive dependency between your two classes. You'd need to use :paste mode, like this:

: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

Then press the Ctrl and D keys together.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top