Kotlin使数据类的构造函数同时接受List和MutableList,但存储它们的可变实例

问题描述 投票:0回答:2

我想制作一个可以同时接受列表和可变列表的数据类,如果列表是MutableList的实例,则直接使其成为属性,如果它是List,则将其转换为MutableList,然后存储它。] >

data class SidebarCategory(val title: String, val groups: MutableList<SidebarGroup>) {
    constructor(title: String, groups: List<SidebarGroup>) :
            this(title, if (groups is MutableList<SidebarGroup>) groups else groups.toMutableList())
}

在上面的代码Platform declaration clash: The following declarations have the same JVM signature中,该类的第二个构造函数引发了错误(第二行)。

我应该如何处理?我应该使用所谓的假构造函数(Companion.invoke())还是有更好的解决方法?

我想制作一个既可以接受列表又可以接受可变列表的数据类,如果该列表是MutableList的实例,则直接使其成为属性,如果它是一个List,则将其转换为...]]] >>

使用Collection代替List,然后制作一个将其设置为等于可变列表的初始化块,如下所示:

data class SidebarCategory(val title: String, groups: Collection<SidebarGroup>) {
    val groups = mutableListOf<>(groups)
}

ListMutableList被映射到相同的java.util.List类(mapped-types),因此从JMV中,看起来SidebarCategory具有两个相同的构造函数。

代替List,可以在第二个构造函数中使用Collection

list kotlin collections immutability constructor-overloading
2个回答
0
投票

使用Collection代替List,然后制作一个将其设置为等于可变列表的初始化块,如下所示:


0
投票

ListMutableList被映射到相同的java.util.List类(mapped-types),因此从JMV中,看起来SidebarCategory具有两个相同的构造函数。

代替List,可以在第二个构造函数中使用Collection

© www.soinside.com 2019 - 2024. All rights reserved.