Primary constructor changes semantics

Given the following class , IntelliJ suggests me to convert the secondary constructor to a primary constructor but that would break class invariant.

class Person {

constructor(email: String) {
    this.email = email
}

var email: String
    set(value) {
        require(value.isNotBlank(), { "The email cannot be blank" })
        field = value
    }
}

After applying the migration, the generated code introduced a subtle bug since the parameter email is written directly to the backing field.

class Person(email: String) {

var email: String = email
    set(value) {
        require(value.isNotBlank(), { "The email cannot be blank" })
        field = value
    }
}

I would like to avoid using a init block since I want to check input parameters before creating the object.
Should the inspection check that the field is using a custom setter ?

1 Like

For me it also seems inconsistent. Maybe you should post a ticket for this bug @emacampolo?

Done https://youtrack.jetbrains.com/issue/KT-22142
Thank you.