提问人:Wafi_ck 提问时间:9/29/2021 最后编辑:Wafi_ck 更新时间:9/29/2021 访问量:33
向 mutableListOf<MyInterface>() 添加两种类型的对象
Adding two types of object to mutableListOf<MyInterface>()
问:
interface ListItem {
val style: ItemStyle
val identifier: ListItemIdentifier?
}
val mutableList = mutableListOf<ListItem>()
我有一个映射到对象和组的列表:
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 ))
}
我需要将该对象添加到我的对象中,但是当我尝试时mutableList
mutableList.addAll(listOf(type , items ))
有错误
Type mismatch.
Required:
Collection<ListItem>
Found:
List<Any>
当我尝试cast listOf时,因为ListItem应用程序崩溃
答:
3赞
broot
9/29/2021
#1
在评论中进行了一些讨论后,我们找到了解决方案。
问题出在这一行。您尝试混合 ,这是一个项目,哪个是项目列表。 不会神奇地将其扁平化,例如:.它将创建如下内容:.这被推断到对象列表,因为有些项目是单个对象,有些是列表。listOf()
type
items
listOf()
[header, item, item, item]
[header, [item, item, item]]
Any
您可以使用以下命令将展合和单个列表:header
items
listOf(header) + items
但在这种情况下,最好只添加两次:mutableList
mutableList.add(type)
mutableList.addAll(items)
评论
List
Collection
<
>
category
archiveItems
[header, item, item, header, item]
mutableList.add(type); mutableList.addAll(items);
mutableList.addAll(...)
Any
ArrayList<ListItem>(...)
...
ListItem
Item
TypeHeader
ListItem
ListItem