interface ListItem {
val style: ItemStyle
val identifier: ListItemIdentifier?
}
val mutableList = mutableListOf<ListItem>()
I have a list that I map to objects and group:
dataList.groupBy { it.type }.forEach { (type, itemList) ->
val type = TypeHeader(name = type.name )
val items = itemList.map { item ->
Item(
title = item.title,
subtitle = item.subtitle
)
}
mutableList.addAll(listOf(type , items ))
}
I need to add that objects to my mutableList
but when I try
mutableList.addAll(listOf(type , items ))
there is a error
Type mismatch.
Required:
Collection<ListItem>
Found:
List<Any>
when I try cast listOf as ListItem app crashes
CodePudding user response:
After some discussion in comments we got to the solution.
The problem is in this listOf()
line. You try to mix type
, which is a single item and items
which is a list of items. listOf()
does not magically flatten this to e.g.: [header, item, item, item]
. It will create something like this instead: [header, [item, item, item]]
. This is inferred to the list of Any
objects, because some items are single objects and some are lists.
You can flatten header
and items
to a single list with:
listOf(header) items
But in this case it is better to just add to mutableList
twice:
mutableList.add(type)
mutableList.addAll(items)