10
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?

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @zsmb13 . Got your point. So, if I declare a primary constructor on Animal class, I will get the same error. Actually, I was finding a way to skip a property in data class that will take part in equals and hashcode methods.
Indeed, placing those properties in the body is the way to go for that - but you still have to initialize them at the time the primary constructor runs in some manner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.