Scala override protected member function

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!

+3
source share
3 answers

In Java, a protected member is available for both subclasses, and the package in which the member is defined in Scala, on the other hand, is visible only to subclasses.

In your case, the code is probably called from outside the class that implements A (for example, from a sheet)

Java,

protected[package_name] def g(i: Int) = println(i)

g() package_name

+1

. . , , .

+2

You do not need to play games with overridetesting only. You can do something like this:

package com.foo.bar

trait MyTrait{
  def stuff(i: Int) = hidden(i) + 1

  protected[bar] hidden(i: Int): Int
}

and then in the test file

package com.foo.bar

class Testing extends Specification{
  "hidden" must{
    //some tests in here
   }

which is another way of saying: "it is hiddendisplayed at the package level and, therefore, anything inside this package can see / check it."

+1
source

All Articles