Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setter like obj.value = "" when the setter has return value?

Tags:

kotlin

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?

like image 554
E. Sundin Avatar asked Dec 22 '16 23:12

E. Sundin


1 Answers

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:

  • How to convert Java assignment expression to Kotlin
like image 190
hotkey Avatar answered Sep 20 '22 23:09

hotkey