我对使用相同对象的方法访问对象的私有内部类有点困惑。这是我在Scala编程中的练习代码(第245-246页):
import Element.elem
abstract class Element {
def contents: Array[String]
def height = contents.length
def width = if(height == 0) 0 else contents(0).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 )
}
override def toString = contents mkString "\n"
}
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 (
val ch: Character,
override val width: Int,
override val height: Int
) extends Element {
private val line = ch.toString * width
def contents = Array.fill(height)(line)
}
def elem(ss: Array[String]) = new ArrayElement(ss)
def elem(s: String) = new LineElement(s)
def elem(ch: Character, w: Int, h: Int) = new UniformElement(ch, w, h)
}
代码与书中的代码相同,但编译器抱怨Element对象底部的三个def elem()
方法。错误说:
私有类ArrayElement将其定义范围作为类型的一部分进行转义 pis.Code_c10s02_CompositionAndInheritance.Element.ArrayElement
但是,如果我从内部类中删除private
修饰符,一切都会变好。这不应该是解决方案,本书的这一部分似乎主要是关于对象内的类进行私有化。这里我的错误是什么?
答案 0 :(得分:14)
出于某种原因,它宁愿失败编译而不是推断一个不太具体但公开的类型。用返回类型声明elem方法。
def elem(ss: Array[String]): Element = new ArrayElement(ss)
def elem(s: String): Element = new LineElement(s)
def elem(ch: Character, w: Int, h: Int): Element = new UniformElement(ch, w, h)