Search code examples
kotlinkotlin-interop

Override setter for variable defined in default constructor


So I have a Kotlin class that looks something like this:

class MyClass {
    var myString: String = ""
        set(value) {
            field = value
            doSomethingINeed()
        }

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

However, Android Studio is warning me that I can use this as a default constructor. When I select that, it changes it to this:

class MyClass(var myString: String)

Now I lose the opportunity to override the setter, because if I make a method called setMyString() I'll get a compiler error.

Is there a way to override the setter if the field is part of the default constructor, or do I have to go with option 1 and just ignore the warning that I get?


Solution

  • The quick fix for it definitely screws things up but the comment is trying to point you in the correct direction. You want to define a primary constructor that accepts just a parameter (not defining a property) and then use that parameter for the property initialization. Something like this:

    class MyClass(myString: String) {
        var myString: String = myString
            set(value) {
                field = value
                doSomethingINeed()
            }
    }