I wanted to create an instance of the attribute and override the protected function g, making it available (function f is for testing).
trait A {
protected def g( i: Int ) = println( i )
def f( i: Int ) = println( i )
}
I created an a1 object
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)
}
and tried to call methods
a1.f(1)
a1.g(3) // this call fails
a1.h(5)
For a1.g (3) I get this error:
<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
But when I define attribute A2, extending A and overriding the methods f and g, instantiate it and call the methods, everything works fine
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)
Why is there a difference between
val a1= new A {
override def g( i: Int ) = super.g(i)
}
and
trait A2 extends A {
override def g( i: Int ) = super.g(i)
}
val a2= new A2 {}
?
Thank!
source
share