How does Kotlin property access syntax work for Java classes (i.e. EditText setText)?
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()