私は継承をそれほど頻繁に使用していないので、なぜ機能しないのかよくわかりません。私のプロジェクトでは、次のものがあります。
保護されたメンバーを持つ基本シール クラス:
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