Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize val property on Kotlin Data Class via Secondary constructor

class Animal {
    val name: String

    constructor(name: String){
        this.name = name // initialized via constructor
    }
}

For the above class in Kotlin I am able to initialize a val property via secondary constructor but the same is not allowed for Data classes

data class User(val name: String, val postalCode: Int) {
    val email: String

    constructor( email: String): this("", 1){
        this.email = email // error: value can not be reassigned
    }

}

What I can't understand is, where is the email property is initialized already as I haven't declared any initializes?

like image 378
mallaudin Avatar asked Feb 04 '23 22:02

mallaudin


1 Answers

If your class has a primary constructor, you have to initialize all of its properties "in the primary constructor" - either by directly initializing them at their declaration:

val email = "[email protected]"

Or in an initializer block:

val email: String

init {
    email = "[email protected]"
}

The compiler forces you to forward all secondary constructor calls to the to the primary constructor, and since the primary constructor already has to initialize all properties inside the class (otherwise calling it would construct a partially initialized instance, like in your code example), it wouldn't make sense to also initialize them in the body of the secondary constructor, especially for a val which cannot be reassigned.

like image 95
zsmb13 Avatar answered Feb 06 '23 14:02

zsmb13