In this blog, we will be discussing the constructors of the Scala.
A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type. A constructor is an instance method that usually has the same name as the class, and can be used to set the values of the members of an object, either to default or to user-defined values.
But this is not the case in Scala.
In Scala, a constructor is not a special method, though it is used to instantiate a scala class.
Scala provides 2 types of constructor.
- Primary constructor
- Auxiliary constructor (Secondary)
A primary constructor is the only entry point to a class because every statement of the class body is a part of the primary constructor.
i.e., The body of the class is the primary constructor and the parameter list follows the class name.
If we do not specify any constructor, the compiler will create a default primary constructor for you.
Apart from the primary constructor, Scala also allows defining Auxiliary constructor.
As the name suggests, Auxiliary constructor is an additional or say secondary constructor which can be defined when we need more than one. That means constructors other than primary constructors are known as Auxiliary constructors.
Let’s take an example to get more understanding of Auxiliary constructor.
Auxiliary constructors are defined using this keyword.
The body of auxiliary constructor should eventually invoke the primary constructor which means, every constructor invocation will end up calling the primary constructor of the class. This is because a primary constructor is the only entry point to a class.
Also, call to this should be the first statement of any auxiliary constructor, otherwise it may lead in the compile-time error. This is a rule which we follow in java as well. But in java, it is not mandatory to call any other constructor.
Also, any or all constructors in java can invoke a superclass constructor, but in Scala, the only primary constructor is responsible to call the superclass constructor.
If you’re from Java background, you’ll feel that the process of declaring a primary constructor in Scala is a bit different. As, In Java, we can easily identify that whether we are in default constructor or not, but in Scala, it is not that easy to identify that. But, once we get comfortable with this approach, it will help us in making our class declarations more concise than Java class declarations.
- Programming in Scala (Third Edition)
- Scala cookbook