Scala protected , and his brothers and sisters protected[this] , protected[pkg] somewhat overwhelming. However, I found a catchy solution using the Java protected philosophy. 1st How a protected member is seen in Java
- They are visible to the subclass (the subclass can be in one package or another package)
- They are visible to any class that is in the same package as the class that the protected member specified.
Obviously, they are visible to the class itself.
But Scala has some limitation on how they are visible to the subclass. By default, they are visible only to the subclass. They are not visible to the package in which the class is declared. However, there are two cases, as they are visible in the subclass.
if the protected member is not qualified (protected from simple), then it is displayed with other instances of the class declaration in the declaration class, as well as with this in the class and subclass, for example
class Base{ protected val alpha ="Alpha"; protected def sayHello = "Hello"; } class Derived extends Base{ def hello = println((new Derived()).sayHello) ; def hello2 = println(this.sayHello); }
if the protected member has this certificate. It is available only with this in the class and subclass; other instances of the declaration of the class or subclass cannot access it, for example
class Base{ protected val alpha ="Alpha"; protected[this] def sayHello = "Hello"; def foo = Console println(new Base().sayHello) // won't compile def bar = Console println(this.sayHello) } class Derived extends Base{ def hello = println(this.sayHello) ; //def hello2 = println((new Derived() .sayHello) // won't compile }
Because Scala does not support access to the protected member at the package level by default. If you want to make it available at the package level, you need to explicitly specify the package, for example. protected[pkg] . Now this protected member is displayed with the declaration of instances of the class / subclass if they are available in classes declared in pkg or lower.
eg.
package com.test.alpha{ class Base{ protected val alpha ="Alpha"; protected[test] def sayHello = "Hello"; // if you remove [test] it won't compile } class Derived extends Base{ val base = new Base def hello = println(base.sayHello) ; }}
Here's how to remember Scala protected
optional
source share