Updated April 4, 2023
Introduction to Constructors in Scala
In this article, we will discuss Scala constructors and its types. Support for constructors in Scala is a bit different than in Java. So the Java developers migrating to Scala might feel a bit out of place while learning or using the Scala constructors. But I am sure it will be fun, as this difference in Scala makes its definitions more concise and accurate. Scala supports two types of constructors Primary Constructor and Auxiliary Constructor.
In this article, we will give you a deep dive into the usage of constructors in scala. So let’s get started.
Types of Constructors in Scala
Primarily there are two types of constructors in Scala:
- Primary Constructor
- Auxiliary Constructor
As we know the constructors in Scala are different than in Java. A scala class can have only one Primary constructor but can have multiple Auxiliary constructors.
Sample definition of class in scala:
Syntax:
class < class-name > (params-list) // class definition
{
// Class body goes here
}
Primary Constructor
Given the class definition given above, Scala provides a default constructor with the class definition. If the constructor is not explicitly defined in the class it covers the complete class body with the exception of methods. Primary constructors can be defined with zero or more parameters. With in the class which inherits another class. Only primary constructors have the ability to call the superclass constructors.
Let’s see some examples with the constructors in action.
Code:
class Person
{
println("Let's call a default primary constructor")
}
Output:
In the example above we have created a class named Person and it is simply printing a message. As we can see that there is no constructor defined in the class. In cases when the constructor is not defined explicitly Scala adds a default constructor with no arguments implicitly. So here, there is no need to define a constructor and perform operations inside it. It saves a lot of time and code space for developers.
Code:
val a = new Person()
val b = new Person
Output:
In the example above, we tried to create instances of the Person class using the implicit constructor. An object of class Person can be created in two ways with an empty parameter or without parameter yielding the same result. We can see that the message is being printed with the object creation as the implicit constructor is called automatically during the object creation from the class.
Let us take a look at another example to further deepen our understanding
Code:
class Person(name: String)
{
println("My name is " + name + ".")
}
Output:
Did you notice any difference in the class definition in comparison to the previous example? Take some time to closely compare the class definitions.
In this example, we are passing arguments to the class. It seems like we can pass the arguments in scala class and it seems logical enough. Now we don’t want the constructor to print the same message every time, rather we would like to print a separate message for each user. So we will have to pass the message from the outside of the instance of the class at the time of the object creation. So we will use a parameterized constructor in scala. The best part of the argument passed in the scala class is that it is treated as an instance variable without mapping it the constructor variables to the actual instance variables. Let’s see what happens if we try to reassign a value to the argument.
Code:
class Person1(name: String)
{
name = "rahul"
}
Output:
If you try to define a class in which you want to assign a value to the variable with the same name as the argument variable, Scala will throw this error as shown in the above picture. So it assures that the argument variable is treated as an instance variable.
Code:
class Person(name: String)
{
var name = "rahul"
}
Output:
So what if you are stuck with the use case that you want to assign the variable to some value and don’t want the value that is coming as an argument. So scala gives a way around this if you want to assign a value to a variable with the same name as argument. We can re-initialize the argument variable with keyword var as shown in the above picture.
Code:
Val p = new Person(" Rahul Bose ")
Output:
So the only modification here is that we are passing an argument with new object creation. It prints the argument we are passing with the user creation. So you can give unique flavors to your class without any major changes in the code.
Auxiliary Constructor
While Scala provides you with the comfort of having a default constructor (primary constructor) without even explicitly defining it, what if you want to have your custom constructor to implement a use case. Well, scala fulfills that requirement with the auxiliary constructor. These constructors provide you with the functionality of constructor overloading in Scala. While there can be only one primary constructor we are free to have as many as auxiliary constructors as we want in the body of a class definition. Isn’t that great!
There is only one basic condition that you have to either call the primary constructor or any other previously defined auxiliary constructor in the first line of code in the method definition of the auxiliary constructor. It means that either directly or indirectly we will end up calling the primary constructor of the class and the primary constructor would be the actual constructor implementing the class instance.
Let us take a look at an example to further understand this. Here let us take a use case that we have a primary constructor that accepts a person’s first name and last name.
Now we get a requirement for adding the user’s middle name while printing the name. So here we can implement auxiliary constructor which can accept three arguments in comparison to the primary constructor which is accepting only two arguments. Let’s implement the auxiliary constructor
Code:
class Person(fname: String, lname: String)
{
def this (fname: String, mname: String, lname: String)
{
this(fname, lname)
println(fname + mname + lname)
}
}
Output:
As we can see in the example the auxiliary constructor is always defined with the keyword this. It is having the basic definition as we discussed above.
In this first line, it calls the primary constructor and then prints the message with the three arguments passed into it. This is a very basic example of constructor overloading in Scala.
Code:
var user = new Person("Rahul ", "Singh ","Bose ")
Output:
As we can see we are creating an instance of users with three arguments and it is printing the name of the person as given.
Recommended Articles
We hope that this EDUCBA information on “Constructors in Scala ” was beneficial to you. You can view EDUCBA’s recommended articles for more information.