Constructor overload
Coming from another language, you may be tempted to declare multiple constructors for your classes. For instance, let’s look at a definition of a User
class in Java:
class User {
private final String name;
private final boolean resetPassword;
public User(String name) {
this(name, true);
}
public User(String name, boolean resetPassword) {
this.name = name;
this.resetPassword = resetPassword;
}
}
Here, the User
class has two constructors, one of which sets a default value for resetPassword
.
Kotlin simplifies this pattern significantly using the default and secondary constructors or leveraging default parameter values:
class User(val name: String, val resetPassword: Boolean) {
constructor(name: String) : this(name, true)
}
The secondary constructor here calls the primary constructor, setting a default value for resetPassword
.
However, it’s usually better to have default...