我想實例化一個特徵並覆蓋受保護的函數g,使其可訪問(函數f用於測試)。scala覆蓋受保護的成員函數
trait A {
protected def g(i: Int) = println(i)
def f(i: Int) = println(i)
}
我創建了一個對象A1
val a1= new A {
override def f(i: Int) = super.f(i)
override def g(i: Int) = super.g(i)
def h(i: Int) = super.g(i)
}
,並試圖調用的方法
a1.f(1)
a1.g(3) // this call fails
a1.h(5)
對於a1.g(3)我得到這個錯誤:
<console>:10: error: method g in trait A cannot be accessed in A{def h(i: Int): Unit}
Access to protected method g not permitted because
enclosing object $iw is not a subclass of
trait A where target is defined
a1.g(3) // this call fails
但是,當我定義擴展一個和重寫方法˚F和克性狀A2,創建它的一個實例,並調用方法,一切工作正常
trait A2 extends A {
override def f(i: Int) = super.f(i)
override def g(i: Int) = super.g(i)
def h(i: Int) = super.g(i)
}
val a2= new A2 {}
a2.f(2)
a2.g(4)
a2.h(6)
爲什麼是有區別
之間val a1= new A {
override def g(i: Int) = super.g(i)
}
和
trait A2 extends A {
override def g(i: Int) = super.g(i)
}
val a2= new A2 {}
?
謝謝!
簡答:這是一個錯誤。 HTTPS://issues.scala-lang。組織/瀏覽/ SI-1352 –