Replace 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 warns me that I can use this as the default constructor. When I choose this, it changes it to this:

class MyClass(var myString: String)

      

Now I lose the ability to override the setter because if I create a method called setMyString()

I get a compiler error.

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

+3


source to share


1 answer


A quick fix for it definitely twists things, but the comment is trying to point you in the right direction. You want to define a primary constructor that only takes a parameter (not defining a property), and then use that parameter to initialize the property. Something like that:



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

      

+7


source







All Articles