Abhijit Sarkar
Abhijit Sarkar

Reputation: 24548

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?

Upvotes: 8

Views: 178

Answers (1)

Kulu Limpa
Kulu Limpa

Reputation: 3541

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;}
}

Upvotes: 6

Related Questions