Defining multiple Constructors in a Scala class
Introduction
If you’re used to creating classes in languages like Java or Python, you can be surprised that in Scala you don’t need to specify it when creating a new class, as Scala will add a default constructor using all defined attributes. For example:
class Example(attribute1: String, attribute2: Int){
def method(): Unit = {
println(attribute1, attribute2)
}
}
val ex1 = new Example("test1", "test2")
ex1.method()
output> (test1, test2)
Adding auxiliar constructors
However, you may want to have multiple constructors that allow you to assign different attributes in multiple ways. Scala allows you to add multiple constructors, so you can create an instance of your class using different sets of attribute. For this, you just overwrite the “this” method. For example:
class Example (attribute1: String, attribute2: Int) {
def this(attribute1: String) {
this(attribute1, 1)
}
def this(attribute2: Int) {
this("Default Attribute 1", attribute2)
}
def method(): Unit = {
println(attribute1, attribute2)
}
}
This class can be used like this:
val ex1 = new Example("Test 0", 0)
ex1.method()
output> (Test 0,0)
----
val ex2 = new Example("Test 1")
ex2.method()
output> (Test 1,1)
-----
val ex3 = new Example(3)
ex3.method()
output> (Default Attribute 1,3)