1
votes

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?

2
You can use Collection instead of List in the second constructorIR42
@IR42 hell yea, but How Collection works in this case? Why List doesn't work? I see almost same signature in them, Collection<out E> List<out E> : Collection<E>Animesh Sahu
Because both List and MutableList are mapped to the same java.util.List class and from JMV it looks like SidebarCategory has two identical constructors. kotlinlang.org/docs/reference/java-interop.html#mapped-typesIR42

2 Answers

2
votes

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.

0
votes

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)
}