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:
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
.