Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I inherit access modifiers from super class in Scala?

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?

like image 630
cdk Avatar asked Mar 22 '23 04:03

cdk


1 Answers

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.

like image 116
ghik Avatar answered Mar 24 '23 17:03

ghik