2

When I compile Code A, I get an error, the system prompt me exists a method name setEditText.

But fun setIsShowEditDialog(isShow:Boolean) is OK without prompt exists a method name setIsShowEditDialog, why?

I have to change fun setEditText(input:String) to fun set_EditText(input:String), it's OK to compile.

But Android Studio prompt me a warning information: Function name 'set_EditText' should not contain underscores , why ?

Code A

class EditDialogState private constructor(context: Context) {

    var isShowEditDialog by mutableStateOf(false)
        private set

    var editText by  mutableStateOf("")
        private  set

    fun setIsShowEditDialog(isShow:Boolean) {    //It's OK
        isShowEditDialog = isShow
    }

    fun setEditText(input:String) {             //Compile Error
        editText = input
    }
}
HelloCW
  • 843
  • 22
  • 125
  • 310
  • 1
    There's no point in what you're doing. Remove the `setEditText` method and the `private set` of the property, and you'll have effectively the same thing. – Jorn Jun 29 '23 at 09:33
  • Thanks! The reason I use `private set` is to be access outside the class, and to be only changed inside the class, would you please see https://stackoverflow.com/questions/76528454/how-can-i-use-destructuring-declarations-in-a-class-in-kotlin – HelloCW Jun 29 '23 at 17:52
  • But I don't know if it's a good way – HelloCW Jun 29 '23 at 17:53

1 Answers1

4

The answer is in the implementation details of Kotlin property setter and getter method names.

class MyTemp {
    var showEditDialog by mutableStateOf(false)
        private set

    var isNewShowEditDialog by mutableStateOf(false)
        private set

    // Will give error
    fun getShowEditDialog(): Boolean {
        return true
    }

    // Will give error
    fun setShowEditDialog(isShow: Boolean) {}

    // Will give error
    fun isNewShowEditDialog(): Boolean {
        return true
    }

    // Will give error
    fun setNewShowEditDialog(isShow: Boolean) {}
}

We can see special handling for variables with the prefix "is".
This causes the difference you are observing.
This is applicable to other types as well like strings.

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
  • Thanks! Is it not a good way to set `var showEditDialog by mutableStateOf(false)` as ` private set` ? would you please the related question at https://stackoverflow.com/questions/76528454/how-can-i-use-destructuring-declarations-in-a-class-in-kotlin – HelloCW Jun 29 '23 at 17:48