Search code examples
listkotlincollectionsimmutabilityconstructor-overloading

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


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?


Solution

  • 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.