How does Kotlin property access syntax work for Java classes (i.e. EditText setText)?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 08:16:15

When generating a synthetic property for a Java getter/setter pair Kotlin first looks for a getter. The getter is enough to create a synthetic property with a type of the getter. On the other hand the property will not be created if only a setter presents.

When a setter comes into play property creation becomes more difficult. The reason is that the getter and the setter may have different type. Moreover, the getter and/or the setter may be overridden in a subclass.

In your case the TextView class contains a getter CharSequence getText() and a setter void setText(CharSequence). If you had a variable of type TextView your code would work fine. But you have a variable of type EditText. And the EditText class contains an overridden getter Editable getText(), which means that you can get an Editable for an EditText and set an Editable to an EditText. Therefore, Kotlin reasonably creates a synthetic property text of type Editable. The String class is not Editable, that's why you cannot assign a String instance to the text property of the EditText class.

To avoid type mismatch, you can use the Factory inner class of Editable class. So you can do now something like:

textview.text = Editable.Factory.getInstance().newEditable("your text")  

Alternatively you could write an extension:

fun String.toEditable(): Editable =  Editable.Factory.getInstance().newEditable(this)

You can then use it as such:

mEditText.text = myString.toEditable()

The android.text.Editable comes from the getText(). It appears to me that the obj.text = value resolution in Kotlin is 2 step process.

  1. Compiler tries to finds a text property or Java method getText from which it infers the property type
  2. For the inferred property type the compiler tries to find corresponding property setter or Java method setText(PropertyType value)

Since in the 1. the inferred type is Editable the editText.text = "value" fails with Type mismatch error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!