Constructor overload
In Java, we're used to having overloaded constructors. For example, let's look at the following Java class, which requires the a
parameter and defaults the value of b
to 1
:
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; Â Â Â Â } }
We can simulate the same behavior in Kotlin by defining multiple constructors using the constructor
keyword:
class User(val name: String, val resetPassword: Boolean) { Â Â Â Â constructor(name: String) : this(name, true) }
The secondary...