What is the difference between textView.setText(string) and textView.text = $string

前端 未结 5 1762
情歌与酒
情歌与酒 2021-01-20 03:46

Hi I am making a app with Kotlin and I found that I can both use

textView.setText(str)

and

textView.text =         


        
5条回答
  •  甜味超标
    2021-01-20 04:19

    They're the same in most cases, basically Kotlin generates a synthetic property for the class attributes based on their getter, which you can use to assign values to and get values from.

    //So, for most cases
    textView.setText("some value");
    //Is the same as
    textView.text = "some value"
    //The second is simply shorter and is the 'kotlin way' of assigning values
    

    Now, here's the catch -

    In most cases, this works fine. But, as mentioned, the synthetic property is generated from the getter, if there is a setter as well, then issues arise. The reason is that the getter and the setter may have different types. For example, EditText has Editable getter, now, kotlin creates a synthetic property text of the type Editable.

    editText.setText("some value"); //Works
    editText.text = "some value" //Won't work, will show an error stating that expected type is Editable
    

提交回复
热议问题