Secondary constructors

There are also secondary constructors; the syntax is similar to primary constructors. The difference is that secondary constructors are declared inside the class body:

class User {

constructor(firstName: String,
lastName: String,
birthYear: Int) {
}
}

Secondary constructors cannot have properties, only constructor parameters. If you need to initialize your fields with constructor parameters, you can do that inside the init block.

You can also have both primary and secondary constructors inside the same class. In that case, the secondary constructor has to call the primary one. This is done with the colon and the this keyword after the secondary constructor declaration:

class User(firstName: String,
lastName: String) {

constructor(firstName: String,
lastName: String,
birthYear: Int) : this(firstName, lastName) {
}
}

Kotlin allows only one primary constructor, but you can have as many secondary constructors as you want:

class User {

constructor(firstName: String,
lastName: String) {

}

constructor(firstName: String,
lastName: String,
birthYear: Int) {
}
}

Notice how it is not needed to call other secondary constructors. Only the primary constructor has to be called from the secondary ones.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.103.30