https://kotlinlang.org logo
#compose
Title
# compose
s

sindrenm

12/08/2020, 10:17 PM
Any downsides to
operator fun <T> State<T>.component1(): T = value
? Being able to destructure a
State
is very useful when the value of the
State
is nullable. Such as:
Copy code
val (content) = viewModel.content.collectAsState()

if (content != null) {
    SomeContent(content)
} else {
    MissingContent()
}
(Using a
StateFlow
here, but applies for any other way of retrieving a
State
as well.) I don't find the property delegate very useful in this situation, as smart-casting can't be done in that case (custom getter and all that). Is this something that would make sense to even add to the standard lib?
z

Zach Klippenstein (he/him) [MOD]

12/08/2020, 10:23 PM
what’s so bad about
Copy code
val content = viewModel.content.collectAsState().value
Much less magical/clever and makes the code very readable if you don’t remember what the destructuring is for
s

sindrenm

12/08/2020, 10:29 PM
Nothing bad about it, I just think the destructuring syntax reads a little better, is all. simple smile
z

Zach Klippenstein (he/him) [MOD]

12/08/2020, 10:55 PM
I guess that’s mostly a matter of opinion, although the use of a fancy syntax feature to reference a single property is unidiomatic and seems like over-engineering to me. If i saw this code in a new codebase, I would have to look into what the destructuring function is doing. Vs just a property reference, which is pretty clear what it’s meant to do.
s

sindrenm

12/08/2020, 11:34 PM
I guess that makes sense. Might be I find the destructuring natural because of React's approach with also grabbing the setter in the same way. Translated, it'd be something like this:
Copy code
val (content, setContent) = viewModel.content.collectAsState()
Where
component2()
would return a setter for the value.
z

Zach Klippenstein (he/him) [MOD]

12/09/2020, 12:54 AM
I think
MutableState
supports that exact syntax. It makes a bit more sense to me there since there are two values (the problem destructuring was designed to solve), but i will admit i’m still not a huge fan of it since i think it’s more readable and not much more boilerplate to write
{ content = foo }
when you need to update it.
a

Adam Powell

12/09/2020, 2:26 AM
The property delegate is the intended way to do what you're doing here
And yes, the value/setter thing is also supported
s

Sean McQuillan [G]

12/09/2020, 6:19 AM
TL;DR pick whatever lhs and operator looks prettiest at the call site, there's no perf concerns