Hi all :android-wave:, I have a query regarding `m...
# compose-android
a
Hi all 👋, I have a query regarding
mutableState
. From the docs (https://developer.android.com/develop/ui/compose/state#state-in-composables), I see that I can create a
mutableState
using either of these syntax.
Copy code
var id: Int? by remember {
  mutableStateOf(null)
}
val setId = { updatedId: Int? ->
  id = updatedId
}
OR
Copy code
val (id: Int?, setId) = remember {
  mutableStateOf(null)
}
I want to pass the method
setId
to function that has the method signature as
setId: (Int?) -> Unit
. The first syntax where the
setId
was manually created by me has the required method signature as expected, but the setter method in the second syntax has the method signature as
(Nothing?) → Unit
. So, I am getting a data type mismatch error. Can anyone please share why this happens, and what is the best way to do this? thank you color
s
You might wanna specify the generic type on your mutableStateOf call instead, so
mutableStateOf<Int?>(null)
. Or even use mutableIntStateOf instead. With that said, I'd personally suggest to never use the destructuring syntax anyway, it's inferior to the delegate option for various reasons.
v
^ The type is only inferred from the value you pass to
mutableStateOf
. For example
Copy code
val id: Int? = mutableStateOf(null)
won't work either.
a
With that said, I'd personally suggest to never use the destructuring syntax anyway, it's inferior to the delegate option for various reasons.
So, the suggestion is to always use the first syntax and manually create the setters?
v
You might not need a named setter at all depending on the use case. My team also mostly prefers not to use delegates either for explicitness
s
The [get, set] syntax has the negative that you're doing the state read right there and then. You are not allowing yourself to take the free wins of sometimes reading the new state from inside a smaller recomposition scope. Plus you are making it impossible to do this https://developer.android.com/develop/ui/compose/performance/bestpractices#defer-reads since even if you then pass
() -> State
, you've read the state at declaration.
☝🏻 1
v
I find it somewhat interesting that the deconstruction syntax is present in the docs without further context. Furthermore it's even written that
These declarations are equivalent
a
The equivalent part was the main source of confusion.
s
They are and should be the same when it comes to correctness, just not performance.