سؤال

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.

نصائح أخرى

I join to ghik's answer and want to add something more.

If you have a trait T { protected def f() } then your extending classes may have f() declared as def f() (which means public as ghik said) or protected def f(), but not private def f().

The general rule is you cannot change the access type to a more restrictive one, you can only widen it, so if you'd have a simple def f() in your trait, the class couldn't even declare it as protected

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top