我不经常使用继承,所以我不确定为什么它不起作用。在我的项目中,我有以下内容:
具有受保护成员的基本密封类:
sealed class TheRoot {
protected def some: String = "TheRoot"
}
它是有一些逻辑的后代:
final case class Descendant() extends TheRoot {
def call: Unit = {
val self: TheRoot = this
self.some // <<- throw compilation error
}
}
上面的编译给了我以下错误:
error: method some in class TheRoot cannot be accessed in TheRoot
Access to protected method some not permitted because
prefix type TheRoot does not conform to
class Descendant where the access take place
self.some
我不太确定从超类调用受保护的成员有什么问题......但是如果我们将它包装到伴生对象中会变得更有趣,它神奇地解决了问题:
sealed class TheRoot {
protected def some: String = "TheRoot"
}
object TheRoot {
final case class Descendant() extends TheRoot {
def call: Unit = {
val self: TheRoot = this
self.some // <<- NO ERROR!
}
}
}
// Exiting paste mode, now interpreting.
defined class TheRoot
defined object TheRoot