I'm learning Scala by working the exercises from the book "Scala for the Impatient". One exercise asks that:
The file Stack.scala contains the definition
class Stack[+A] protected (protected val elems: List[A])
Explain the meaning of the
protected
keywords.
Can someone help me understand this? protected
obviously makes sense for member variables but what implication does it have in a class definition?
Normally, in both Java and Scala, when a member of a class or trait is private or protected, this means that the access is restricted to the class or trait. Access is not restricted to individual instances; an instance of a class can access the same member in other instances of the same class.
Use the with Keyword in ScalaThis keyword is usually used when dealing with class compositions with mixins. Mixins are traits that are used to compose a class. This is somewhat similar to a Java class that can implement an interface.
In Scala, writing
class Stack[+A](elems: List[A])
also implements a default constructor. If you know Java, then in Java this would be something like
class Stack<A> {
private List<A> elems;
public Stack<A>(List<A> elems){this.elems = elems;}
}
Now, you have two protected
keywords in your example:
protected val elems: List[A]
protected (/*...*/)
The first makes the variable elems
protected, meaning it can only be accessed (and shadowed) by subclasses of Stack[+A]
.
The second makes the constructor protected, meaning that a new Stack
instance can only be created by subclasses of Stack[+A]
.
Again, the equivalent Java code would be something like
class Stack<A> {
protected List<A> elems;
protected Stack<A>(List<A> elems){this.elems = elems;}
}
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