Scala companion object with abstract class -
i'm reading book programming in scala (second edition) martin odersky , have problem examples in chapter 10.
this file @ end of chapter:
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( ( (line1, line2) <- this.contents zip that.contents ) yield line1 + line2 ) }
the compiler says this:
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( ^
if remove class element
beginning complains element type not found when try subclass it.
i found couple topics here discussing chapter book couldn't use of proposed solutions there.
what did miss?
regards, norbert
first, declare class element twice - remove first line, confusing things (this doesn't cause errors me - if you, can show more info on error?). should fix override errors. second, method elem
companion object isn't automatically visible in class. either prefix element
wherever used or - better - add import line @ start of class:
object element { ... } abstract class element { import element._ ... }
edit: ah, might have idea why error when leave off first line. if trying in repl , entering 1 line (or 1 declaration) @ time, might hit issue because repl doesn't forward referencing required. try pasting code in @ once (using ":paste" in repl).
Comments
Post a Comment