Primary constructor changes semantics


#1

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 ?


#2

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


#3

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