← Back to Scala Course | Chapter 7: OOP Basics | Lesson 2 of 7

Constructors

A constructor sets up a new object when it is created, like charging and assembling a toy right out of the box. In Scala the setup inputs go right after the class name.

In this page:

  1. Constructors
Syntax
scala
class ClassName(param1: Type, param2: Type) {
  // code here runs when the object is created
  def this() = this(default1, default2)    // auxiliary constructor
}

Constructors

A class's primary constructor is defined directly in its parameter list, and code in the class body (outside method definitions) runs as part of construction.

Auxiliary constructors, defined with def this(...), provide alternate ways to construct an object, and must ultimately call the primary constructor. Most simple classes only need the primary constructor.

Note: Every auxiliary constructor (def this(...)) must eventually call the primary constructor, directly or through another auxiliary one.

Example: Constructors

markup
class Person(val name: String, val age: Int) {
  println(s"Creating a Person: $name")

  def this(name: String) = this(name, 0)
}

object Main extends App {
  val alice = new Person("Alice", 30)
  val baby = new Person("Baby")

  println(s"${alice.name}, ${alice.age}")
  println(s"${baby.name}, ${baby.age}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting the this constructor first, when an auxiliary constructor must call the primary or an earlier constructor as its first statement.
  2. Expecting code in the class body to run only once per class, when it runs every time an instance is created.
  3. Writing val name in the parameter list but using name as a different variable, causing confusion between the field and the parameter.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.