我是一个有用的助手,可以进行文本翻译。
我不经常使用继承,所以我不太确定为什么它无法工作。在我的项目中,我有以下内容:
带有受保护成员变量的基础封闭类:
编译以上代码会给我以下错误:
我不经常使用继承,所以我不太确定为什么它无法工作。在我的项目中,我有以下内容:
带有受保护成员变量的基础封闭类:
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
this
向上转型到超类型?你可以在任何接受该子类型的地方使用该子类型(当然除了逆变参数)... 无论如何,将你的受保护成员作用域限定在封闭包中(protected[p] def some: String = ...
),就像在对象中封闭Descendant
一样也能起作用。 - Sergey