Primary constructors are defined inline with the class declaration using the following syntax:
class Student public constructor(_firstName: String, val lastName: String) {
...
}
If the constructor does not require any visibility modifiers or annotations, the constructor keyword can be omitted to reduce the boilerplate:
class Student (_firstName: String, val lastName: String) {
}
Within a primary constructor, we can pass arguments and define properties. If the constructor does not require any arguments or properties, then the parentheses can be omitted. In this case, a default empty constructor will be generated by the compiler, allowing the class to be instantiated as if it did have a defined constructor.
The following snippet demonstrates a School class without any declared constructor:
class School {
var name = ""
}
Though School has no constructor defined, we can still instantiate it. In the following snippet, we see that we can still instantiate an instance of School using the generated empty constructor:
fun main(args: Array<String>) {
val school = School()
}
The existence of a compiler-generated empty constructor ensures that any class we define can be instantiated, even if we don't have to write the boilerplate primary constructor code. In the next section, we'll look at adding multiple constructors to our classes.