Scala Constructor
In scala, constructor is not special method. Scala provides primary and any number of auxiliary constructors. We have explained each in details in the following example.
Scala Default Primary Constructor
In scala, if you don’t specify primary constructor, compiler creates a constructor which is known as primary constructor. All the statements of class body treated as part of constructor. It is also known as default constructor.
Scala Default Primary Constructor Example
Output:
Hello from default constructor
Scala Primary Constructor
Scala provides a concept of primary constructor with the definition of class. You don’t need to define explicitly constructor if your code has only one constructor. It helps to optimize code. You can create primary constructor with zero or more parameters.
Scala Primary Constructor Example
Output:
101 Rama
Scala Secondary (auxiliary) Constructor
You can create any number of auxiliary constructors in a class. You must call primary constructor from inside the auxiliary constructor. this keyword is used to call constructor from other constructor. When calling other constructor make it first line in your constructor.
Scala Secondary Constructor Example
Output:
101 Rama 20
Scala Example: Constructor Overloading
In scala, you can overload constructor. Let’s see an example.
Output:
101 100 100 India