问题
I want to make a data class which can accept both list and mutable-list and if the list is instance of MutableList then directly make it a property else if it is a List then convert it into a MutableList and then store it.
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())
}
In the above code Platform declaration clash: The following declarations have the same JVM signature
error is thrown by the secondary constructor of the class (2nd line).
How should I approach this? Should I use a so called fake constructor (Companion.invoke()) or is there any better work-around?
回答1:
List
and MutableList
are mapped to the same java.util.List
class (mapped-types), so from JMV it will look like SidebarCategory
has two identical constructors.
Instead of List
, you can use Collection
in the second constructor.
回答2:
Use Collection
instead of List
, and then make an init block that sets it equal to a mutable list, as so:
data class SidebarCategory(val title: String, groups: Collection<SidebarGroup>) {
val groups = mutableListOf<>(groups)
}
来源:https://stackoverflow.com/questions/62015248/kotlin-make-constructor-of-data-class-accept-both-list-and-mutablelist-but-store