In Scala, a class can have one primary constructor and multiple auxiliary constructors. The primary constructor is responsible for class initialization, while auxiliary constructors are helpful in providing additional constructors that delegate some of the initialization to the primary constructor. Let’s discuss them in detail:
1. Primary Constructor:
The primary constructor is not defined separately like in Java or other languages. Instead, it is integrated into the class definition. It is the constructor that is executed when you create a new instance of the class. The main responsibilities of the primary constructor are to initialize the class variables and execute any code present in the class body.
In Scala, you can define a primary constructor by specifying the parameters directly in the class definition itself. Here’s an example of a primary constructor in Scala:
class Person(name: String, age: Int) {
// Class body
}
Usage:
val person = new Person("John", 30) // Creates a new instance of the Person class with the primary constructor
2. Auxiliary Constructor:
Auxiliary constructors, also known as secondary constructors, are additional constructors that can be defined inside the class body. They are useful when you want to create objects with different sets of parameters. Auxiliary constructors must start with the ‘this‘ keyword and can call another auxiliary constructor or the primary constructor.
Here’s an example of a few auxiliary constructors:
class Person(name: String, age: Int) {
//Auxiliary constructor
def this(name: String) {
this(name, 0) // Calling the primary constructor
}
//Another auxiliary constructor
def this(age: Int) {
this("Unknown", age) // Calling the primary constructor
}
//Another auxiliary constructor
def this() {
this("Unknown", 0) // Calling the primary constructor
}
}
Usage:
val person1 = new Person("John", 30) // Creates a new instance of the Person class with the primary constructor
val person2 = new Person("Michael") // Creates a new instance of the Person class with the first auxiliary constructor
val person3 = new Person(35) // Creates a new instance of the Person class with the second auxiliary constructor
val person4 = new Person() // Creates a new instance of the Person class with the third auxiliary constructor
In summary, the primary constructor is essential for class initialization and is defined by specifying the constructor parameters directly in the class definition. In contrast, auxiliary constructors are additional constructors in the class body defined with the ‘this‘ keyword and can call other auxiliary constructors or the primary constructor.