An interesting trick some may not know about using `MutableState`. When using state as a delegate yo...
a
An interesting trick some may not know about using
MutableState
. When using state as a delegate you often have the compiler refuse to do smart casts (e.g.
if (x != null) { x.function() }
doesn’t compile). The alternative is to just assign the state value to the variable (i.e.
var xState by remember { mutableStateOf(…) }
and then
val x = xState.value
). A better alternative is to use destructuring on the state - it turns out
MutableState.component2
returns a setter of the value. So you can do:
Copy code
val (x, setX) = remember { mutableStateOf(...) }
and then you have the value in
x
(which smart casts will work on), and a setter in
setX
. This is particularly convenient with composables like
TextField
.
🙌 2
thank you color 4
a
A caveat is that without a recomposition
x
won’t be updated even after you call the setter with a new value, which isn’t the case if you use
var x by remember { mutableStateOf(…) }
.
a
Indeed. You could define
Copy code
operator fun <T> MutableState<T>.component3() = this
and use
Copy code
val (x, setX, xState) = remember { mutableStateOf(...) }
😉
kodee frightened 3
k
How do i get to the level where all this makes sense 🙂 ? I'm currently at the level where i just know how to write var x by remember { mutableStateOf(…) }.
z
i wish Kotlin had something like swift’s
if let x = xState