Primary constructors I
- Recall that a constructor is a special member function that when called will create a new instance of that class. There are two kinds of constructors: primary and secondary. A class can have zero or one primary constructor, and zero or more secondary constructors.
The primary constructor, if exists, is declared in the class header right after the class name, by using the word
constructor
followed by a comma-separated list of “parameter: type” declarations and enclosed in a pair of parentheses, like this:class Person constructor(_firstName: String, _lastName: String, _age: Int) { ... }
In fact, when the word
constructor
is not preceded by annotations or visibility modifiers, like in the declaration above, it can be safely dropped. So the above declaration is equivalent to the shorterclass Person(_firstName: String, _lastName: String, _age: Int) { ... }