Constructors
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: