Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the implication of protected keywords in class definition in Scala?

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?

like image 655
Abhijit Sarkar Avatar asked May 03 '15 22:05

Abhijit Sarkar


People also ask

What is protected def Scala?

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.

What is with in Scala?

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.


1 Answers

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;}
}
like image 191
Kulu Limpa Avatar answered Nov 04 '22 07:11

Kulu Limpa