How to create multiple class constructors in Scala

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.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.