2013-08-19 88 views
1

我讀斯卡拉(第二版)由Martin Odersky的書編程和我有在第一章的例子問題斯卡拉同伴對象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它抱怨的元素類型我當我試圖對它進行子類化時,沒有找到它。

我發現這裏幾個話題已經討論從本章的這本書,但我不能使用任何提出的解決方案存在的。

我錯過了什麼?

問候, 諾伯特

回答

4

首先,聲明類元素的兩倍 - 刪除第一行,它只是混亂的事情(這不會對我造成任何錯誤 - 如果它不適合你,你可以展示我們有關錯誤的更多信息?)。這應該修復覆蓋錯誤。二,方法elem從同伴對象不在類自動可見。無論是與Element前綴它無論在何處使用或 - 更好 - 在類的開頭添加一個導入行:

object Element { 
    ... 
} 

abstract class Element { 
    import Element._ 
    ... 
} 

編輯:啊,你爲什麼當你離開關得到一個錯誤,我可能有一個想法第一行。如果你想這個在REPL,每次進入這一條線(或一個聲明),那麼你可能打這個問題,因爲REPL不喜歡需要向前引用。嘗試粘貼所有的代碼在一次(使用:在REPL「粘貼」)。

+0

謝謝你,問題是,我把進口錯了地方。在書中它說我必須把它放在課外。它現在有效。 ;) – norbertk