By Alvin Alexander. Last updated: February 22, 2021
Scala constructors FAQ: How do I create a Scala class with multiple constructors (secondary constructors)?
The Scala approach to defining multiple class constructors is a little different than Java, but somewhat similar. Rather than try to explain this in words, I just created some example source code to demonstrate how this works.
Here's some source code to demonstrate the Scala "multiple constructors" approach:
package tests object MultipleConstructors { def main(args: Array[String]) { // (1) use the primary constructor val al = new Person("Alvin", "Alexander", 20) println(al) // (2) use a secondary constructor val fred = new Person("Fred", "Flinstone") println(fred) // (3) use a secondary constructor val barney = new Person("Barney") println(barney) } } /** * The main/primary constructor is defined when you define your class. */ class Person(val firstName: String, val lastName: String, val age: Int) { /** * A secondary constructor. */ def this(firstName: String) { this(firstName, "", 0); println("\nNo last name or age given.") } /** * Another secondary constructor. */ def this(firstName: String, lastName: String) { this(firstName, lastName, 0); println("\nNo age given.") } override def toString: String = { return "%s %s, age %d".format(firstName, lastName, age) } }
If you run this example program as is, you'll get the following output:
Alvin Alexander, age 20 No age given. Fred Flinstone, age 0 No last name or age given. Barney , age 0
I'm not going to write any more about the Scala constructors approach today, but if you have any questions, comments, or corrections about this example, just leave a note in the Comments section below.