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

匆匆过客 提交于 2020-08-10 05:04:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!