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

ste

01/13/2022, 1:30 PM
I'm getting a
ClassCastException
with the following minimal snippet:
Copy code
var something by rememberSaveable { mutableStateOf(0) }
val value by rememberSaveable(something) { mutableStateOf("Hello") }
val somethingElse by rememberSaveable { mutableStateOf(false) } // !!!

println("value: $value") // !!!

Box(
    modifier = Modifier
        .fillMaxSize()
        .clickable { something += 1 }
)
However, after
something
is changed, it throws
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
on configuration change. I know the example doesn't make sense, but is this a bug or whatsoever?
👀 1
It looks like it's messing
value
and
somethingElse
value restores
a

Andrey Kulikov

01/13/2022, 4:22 PM
if you have a stable reproducible example please file a bug!
z

Zach Klippenstein (he/him) [MOD]

01/13/2022, 4:24 PM
i’ve got a test that reproduces
removing the key for
value
, or adding one to
somethingElse
, seems to avoid the crash
looks like somehow the saved values are in the wrong order in the registry’s list
so it looks like this happens because `value`’s saved value provider is removed then re-added to the list of providers when the key changes. So after the first composition, the list is
{0, "Hello", false}
, then after the button is clicked, it’s
{1, false, "Hello"}
. If you haven’t filed a bug yet, i will.
a

Andrey Kulikov

01/13/2022, 4:57 PM
indeed, thanks for the investigation. feel free to assign a bug on me, I will take a look
z

Zach Klippenstein (he/him) [MOD]

01/13/2022, 5:02 PM
a

Andrey Kulikov

01/13/2022, 5:08 PM
a workaround would be to reorder the val declarations so the one with keys is defined the last one. meaning that
somethingElse
is defined before
value
in your example
z

Zach Klippenstein (he/him) [MOD]

01/13/2022, 5:11 PM
I think another workaround would be to hoist all three values into a separate object and just use
rememberSaveable
once. Only then you’d need to manage re-initializing the
"Hello"
state when
something
changed, but since i’m guessing your real code that triggered this is more complex i’m guessing you might eventually want to factor out a state holder anyway.
s

ste

01/13/2022, 5:36 PM
Thanks for investigating!
3 Views