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:
Syntax
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
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}")
}
Login to try C/C++/Java/PHP code in the editor
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
- Putting the
thisconstructor first, when an auxiliary constructor must call the primary or an earlier constructor as its first statement. - Expecting code in the class body to run only once per class, when it runs every time an instance is created.
- Writing
val namein the parameter list but usingnameas 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: