向 mutableListOf<MyInterface>() 添加两种类型的对象

Adding two types of object to mutableListOf<MyInterface>()

提问人:Wafi_ck 提问时间:9/29/2021 最后编辑:Wafi_ck 更新时间:9/29/2021 访问量:33

问:

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应用程序崩溃

列表 科特林 可变

评论

0赞 broot 9/29/2021
您确定您提供了完整的错误消息吗? 需要时应该没问题,我想问题出在类型参数(用 和 括起来),但你没有提供它们。什么是和?ListCollection<>categoryarchiveItems
0赞 Wafi_ck 9/29/2021
我的错。我更新了我的问题。
1赞 broot 9/29/2021
好的,您是否可以尝试创建一个列表,例如:等?在这种情况下,您确实需要这样做:.[header, item, item, header, item]mutableList.add(type); mutableList.addAll(items);
1赞 Damian Piszka 9/29/2021
在你给出论点。您需要声明您提供的数据类型作为参数。将 where are aguments 用于构造函数。mutableList.addAll(...)AnyArrayList<ListItem>(...)...ListItem
1赞 Sweeper 9/29/2021
两者都实现吗?如果没有,为什么要将它们都添加到 s 列表中?ItemTypeHeaderListItemListItem

答:

3赞 broot 9/29/2021 #1

在评论中进行了一些讨论后,我们找到了解决方案。

问题出在这一行。您尝试混合 ,这是一个项目,哪个是项目列表。 不会神奇地将其扁平化,例如:.它将创建如下内容:.这被推断到对象列表,因为有些项目是单个对象,有些是列表。listOf()typeitemslistOf()[header, item, item, item][header, [item, item, item]]Any

您可以使用以下命令将展合和单个列表:headeritems

listOf(header) + items

但在这种情况下,最好只添加两次:mutableList

mutableList.add(type)
mutableList.addAll(items)