![]() |
VOOZH | about |
Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements (i.e. instructions). Statements are executed at the time of object creation. In Scala Program, the constructors other than the primary constructor are known as Auxiliary Constructors. We are allowed to create any number of auxiliary constructors in our Scala class, but a scala class contains only one primary constructor.
Auxiliary constructors are defined as methods in the class with the keyword this. We can describe multiple auxiliary constructors, but they must have different parameter lists.
Syntax :
def this(......)
Let's try to understand Auxiliary constructors with help of some examples.
Example #1: Using one Auxiliary Constructor
Output:
Language name: Scala Topic name: Constructor Total number of articles: 4
In above example, as we can see only one auxiliary constructor is used and primary constructor invoked in that auxiliary constructor. After creating object of GFG class(obj), show() function will be called and print the result.
Example #2: Using more than one Auxiliary Constructor.
Output:
Language name: Total number of employee: 0 Language name: GeeksForGeeks Total number of employee: 0 Language name: GeeksForGeeks Total number of employee: 42
In above example, as we can see two auxiliary constructors are created with different parameters. Auxiliary constructor invoked primary constructor and another auxiliary constructor invoked previously defined auxiliary constructor.