Auxiliary constructor in Scala

Scala-Constructor-Auxillary

Before starting with auxiliary constructor I request you to first visit my previous blog  Primary Constructor in Scala.
Scala has two types of constructor
i ) primary constructor.
ii ) auxiliary constructor (secondary constructor).

A scala class can contain zero or more auxiliary constructor.
The auxiliary constructor in Scala is used for constructor overloading and defined as a method using this name.
The auxiliary constructor must call either previously defined auxiliary constructor or primary constructor in the first line of its body. Hence every auxiliary constructor invokes directly or indirectly to a primary constructor.

we can call the primary constructor or other auxiliary constructor using this.

Here is an example,

See the above code, when we create an object using zero-argument auxiliary constructor then there is the first statement this(0,””,0.0) which will call to a primary constructor. Hence first Primary constructor body will be executed then after auxiliary constructor body.

we can also call directly to the primary constructor.

When you compile Employee.scala using scalac Employee.scala and after convert it into java code using javap Employee.class.
see the below-generated java code.

Compiled from "Employee.scala"
public class Employee {
  public Employee(int, java.lang.String, double); //java parameterized constructor.
  public Employee();   // java default constructor.
}

Now create Scala class with a primary constructor and multiple auxiliary constructors

see the above output when we create an instance with the help of zero arguments auxiliary constructor. Zero argument constructor call to One argument auxiliary constructor and One argument constructor to a Primary constructor. So the primary constructor body would execute first then after one argument constructor body then after zero arguments.
Now,

When you invoke more than one time this in the auxiliary constructor then it will invoke apply() in the class,

If an apply method does not define in the class and call more than one times this in the auxiliary constructor then it will give compile time error.

 

 

In Scala, We can also create a primary constructor with a default value. If you don’t provide value then it will take default value which is provided in the Primary constructor.  Otherwise the value we provide when an instance created with the help of a parameter name of the class.

Here is an example,

If we provide a wrong parameter name of the class at the time of instance creation then it will give the compile-time error.

 

Please comment, if you have any doubt or suggestion.
thank you 🙂

knoldus-advt-sticker

1 thought on “Auxiliary constructor in Scala

Leave a Reply

%d bloggers like this: