Kotlin使数据类的构造函数同时接受List和MutableList,但存储它们的可变实例 [英] Kotlin make constructor of data class accept both List and MutableList but store a mutable instance of them

查看:236
本文介绍了Kotlin使数据类的构造函数同时接受List和MutableList,但存储它们的可变实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个可以同时接受列表和可变列表的数据类,如果列表是MutableList的实例,则直接使其成为属性,如果它是List,则将其转换为MutableList,然后存储它。

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

在上面的代码中,平台声明冲突:以下声明具有相同的JVM签名错误。

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

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

How should I approach this? Should I use a so called fake constructor (Companion.invoke()) or is there any better work-around?

推荐答案

List MutableList 映射到相同的 java.util.List 类(映射类型),因此从JMV看起来像 SidebarCategory 具有两个相同的构造函数。

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.

您可以使用 Collection 代替 List 第二个构造函数。

Instead of List, you can use Collection in the second constructor.

这篇关于Kotlin使数据类的构造函数同时接受List和MutableList,但存储它们的可变实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆