Kotlin make constructor of data class 接受 List 和 MutableList 但存储它们的可变实例

Kotlin make constructor of data class accept both List and MutableList but store a mutable instance of them

我想制作一个数据class,它可以同时接受列表和可变列表,如果列表是 MutableList 的实例,则直接将其设为 属性 否则,如果它是一个列表,则将其转换成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 错误是由 class 的辅助构造函数抛出的(第 2 行)。

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

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

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

ListMutableList 映射到相同的 java.util.List class (mapped-types),所以从 JMV 来看它看起来像 SidebarCategory 有两个相同的构造函数。

您可以在第二个构造函数中使用 Collection 而不是 List