5

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?

AdamMc331
  • 16,492
  • 10
  • 71
  • 133
  • 1
    Please report it as a bug in the Kotlin plugin at https://youtrack.jetbrains.com/issues/KT – voddan May 21 '17 at 05:15
  • Is this a bug, though? Seems like it was just my misunderstanding of how the language works @voddan – AdamMc331 May 21 '17 at 05:21
  • 3
    Any IDEA or AS refactoring is supposed to change the code without changing its semantics. In your case semantics was broken since it erased your custom setter. That's why I think it is a bug. – voddan May 21 '17 at 06:00
  • 1
    @voddan Thanks for the recommendation. I've just put in the ticket - https://youtrack.jetbrains.com/issue/KT-17996 – AdamMc331 May 21 '17 at 15:26

1 Answers1

10

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()
        }
}
zienkikk
  • 2,404
  • 1
  • 21
  • 28
  • Thank you! This is the solution I needed and what I've implemented. Please see the comments under the question for a discussion on the file conversion bug and a link to the Kotlin ticket. – AdamMc331 May 21 '17 at 15:28