I want to use `value class` with `String` as `key`...
# compose
w
I want to use
value class
with
String
as
key
for
LazyColumn
item. Unfortunately I received
Type of the key testString is not supported. On Android you can only use types which can be stored inside the Bundle
Is there any chance to add custom
Saver
to
LazyColumn
or to add support for
value class
?
Copy code
@JvmInline
value class Id(val value: String)
Copy code
val items = listOf(Id("testString"), Id("123"))
LazyColumn {
    items(
        items = items,
        key = { index -> items[index] }, // `items[index].value` is not obvious imho
    ) { index ->
        Text(items[index].value)
    }
}
f
You can use
Copy code
key = { index -> items[index].value },
w
Yes, I know but it's not obvious
f
what is not obvious?
w
Using
.value
getter for
value class
which should be transparent in many cases. But it's not in this case
f
I plugged this into a sample app of mine and it compiled fine
Copy code
@JvmInline
value class Id(val value: String)

@Composable
private fun WeatherForecast(
    state: WeatherState,
    modifier: Modifier = Modifier,
) {
    LazyVerticalGrid(
        columns = GridCells.Adaptive(
            minSize = WeatherCardWidth,
        ),
        modifier = modifier,
        contentPadding = PaddingValues(all = MarginDouble),
        horizontalArrangement = Arrangement.spacedBy(MarginDouble),
        verticalArrangement = Arrangement.spacedBy(MarginDouble),
    ) {
        state.forecastItems.forEach { dayForecast ->
            item(
                key = Id(dayForecast.header.id),
                span = { GridItemSpan(maxLineSpan) }
            ) {
                ForecastHeader(
                    state = dayForecast.header,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = MarginDouble),
                )
            }
            items(
                items = dayForecast.forecast,
                key = { hourForecast -> Id(hourForecast.id.toString()) }
            ) { hourForecast ->
                ForecastWeatherCard(
                    state = hourForecast,
                    modifier = Modifier.fillMaxWidth(),
                )
            }
        }
    }
}
if you are getting an error, you could try to make your value class parcelable with
@Parcelize