How to use setter as obj.value = "" when setter has a return value?

I have android EditText on which I set the text property.

Normally I would use:

editText.text = "Mars" 

But setter returns Editable, so it seems that Kotlin is trying to replace the returned Editable with String, which fails.

So the "workaround":

 editText.setText("Mars") 

Are there more beautiful ways (instead of setText() ) to set the text when using this type of setter?

+5
source share
1 answer

In Kotlin, assignments are not expressions. Assignment expressions have few real use cases and, as a rule, impair code readability, not to mention if (a = b) errors, therefore they are not taken into account. You can find more comments from the Kotlin team in this discussion .

It is actually not possible to get the value returned by the Java installer using the property = value syntax, and the workaround you described is a valid way to get that value.


Kotlin property setters, in turn, cannot return a value, and, for example, the general Java idiom of this return value for a call chain is expressed using Kotlin with a 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:

+12
source

Source: https://habr.com/ru/post/1261747/


All Articles