Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private and protected constructor in Scala

Tags:

scala

I've been curious about the impact of not having an explicit primary constructor in Scala, just the contents of the class body.

In particular, I suspect that the private or protected constructor pattern, that is, controlling construction through the companion object or another class or object's methods might not have an obvious implementation.

Am I wrong? If so, how is it done?

like image 959
Don Mackenzie Avatar asked Nov 13 '09 16:11

Don Mackenzie


People also ask

Can constructor be private or protected?

No, Constructors can be public , private , protected or default (no access modifier at all). Making something private doesn't mean nobody can access it. It just means that nobody outside the class can access it. So private constructor is useful too.

What is a protected constructor?

A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor. This sounds a bit chicken-and-egg, but is sometimes useful when implementing class factories.

How do you make a Scala constructor private?

In Scala, only a primary constructor is allowed to invoke a superclass constructor. In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list.

What are the types of constructor in Scala?

There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.


1 Answers

You can declare the default constructor as private/protected by inserting the appropriate keyword between the class name and the parameter list, like this:

class Foo private () {    /* class body goes here... */ } 
like image 56
Aleksander Kmetec Avatar answered Oct 11 '22 03:10

Aleksander Kmetec