Suppose I have the following trait and class extending that trait
trait T { protected def f() }
class C extends T { def f(): println("!") }
object Main extends App {
val c = new C
c.f() // should be a compile error
}
I declared f
as protected
in the declaration for T
so that it can be called from inside the scope of C
, but not by others. In other words, C.f()
should be a compile error. I thought the protected
modifier from T
would carry over, but it doesn't.
I could just redeclare C.f()
as protected
in the declaration for C
, but I'd rather not have to repeat myself. Is there any other way to do this in Scala?
Short answer: no.
Not specifying an access modifier does not mean "inherit access modifier", it means "public". Scala has no public
keyword and if it didn't work like this, there would be no way to actually make a protected member public when overriding.
In other words, you have to repeat the protected
modifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With