I have an android EditText which I'm setting the text property on.
Normally I'd use:
editText.text = "Mars"
But the setter returns a Editable so it seems Kotlin is trying to replace the returned Editable with a String which fails.
So the "workaround" is:
editText.setText("Mars")
Are there any prettier ways (instead of setText()
) of setting the text when this type of setter is used?
In Kotlin, assignments are not expressions. Assignment expressions have few real use cases and tend to worsen the code readability, not to mention the if (a = b)
bugs, so they were left out of the language. You can find more comments from the Kotlin Team in this discussion.
It is actually impossible to get the value returned from a Java setter using the property = value
syntax, and the workaround you described is the valid way to get that value.
Kotlin property setters, in turn, cannot return a value, and, for example, a common Java idiom of returning this
value for the calls chaining is expressed with Kotlin functions with receiver:
MyClass c = new MyClass()
.setFoo(x)
.setBar(y)
.setBaz(z);
Kotlin (using apply
):
val c = MyClass().apply {
foo = x
bar = y
baz = z
}
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With