Scala – Auxiliary Constructor

In the previous post, we have learnt primary constructor in scala. Now, we will learn about Auxiliary constructor in scala.

In scala, constructor other than primary constructor are called Auxiliary Constructor or secondary constructor. We can have multiple constructors in a class and there are few points below to understand them better.

  • Auxiliary constructors are the methods in the class which can be created with def this(…). That means one constructor calls another constructor with method named this.
  • There can be multiple Auxiliary constructors but all should have the different signature (parameter list). It can have zero or one or more parameters.
  • Each constructor must call one of the previously defined constructor and placed it as first line of its body.
  • Auxiliary constructor can call either primary constructor or another auxiliary constructor by using this name.Hence, every auxiliary constructor invokes directly or indirectly to a primary constructor.

Example 1 – Create a primary constructor and an auxiliary constructor

Let’s understand this with an example where we define a class having a primary constructor and a zero arguments auxiliary constructor.

Now, create an object with no parameter and it should call auxiliary constructor which will make a call to primary constructor. In other words, first primary constructor will be executed and then auxiliary constructor.

If object is created with parameters, then only primary constructor will be called.

Example 2 – Create a primary constructor and multiple auxiliary constructors.

Create an object with 2 parameters.

In the above example, first 2 arguments constructor will be called which is having zero argument constructor as its first line and it will call primary constructor. So, it will have execution sequence as Primary constructor –> Zero arguments constructor –> 2 arguments constructor.

So far, we have discussed the constructor overloading with auxiliary constructors. Is it possible to perform constructor overloading without auxiliary constructor or by using only primary constructor?

Answer is Yes, it is possible as Scala has introduced a new feature called as “Scala’s Default Arguments concept” from version 2.9.

Example: Let’s redefine the Employee class with default parameters as given below.

Test1 – Create an object without arguments.

Test 2 – Change the first name.

Test 3 – Change the last name.

Scala - Primary Constructor
Scala - Method Overloading
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *