如何将主构造函数中接收到的列表转换为 MutableList,以便我们可以将 class 委托给 MutableList

How to cast the List received in the primary constructor to MutableList so that we can delegate the class to MutableList

我想通过添加一些线程安全功能来实现 kotlin 的 MutableList 接口,如果我想实现 MutableList 接口并仅覆盖对线程不安全的内容,因此我选择了委托。

每次使用 List.toMutableList() 它 returns 包含数据中所有项目的新 MutableList 实例。

class ThreadSafeList<E> constructor(data: List<E>): MutableList<E> by data.toMutableList() //different reference (new object created when using toMutableList())
{
    private val data = data.toMutableList() //different reference (new object created when using toMutableList())
    ...

    //default constructor when no argument is supplied
    constructor(): this(listOf())

    //override, locks & stuffs for thread safety
}

期望: 我想在构造函数本身中将 List 转换为 MutableList,以便实现委托持有与 val 数据持有相同的引用,但我无法找到如何这样做。

经过大量研究,我终于找到了一种方法。

我会解释我是如何做到的,它可能会帮助任何遇到这个问题的人,

class ThreadSafeList<E> private constructor(private val data: MutableList<E>): MutableList<E> by data
{
    // default constructor, when no elements are passed
    constructor(): this(mutableListOf())

    companion object {
        // constructor for a list to use its elements for the purpose
        operator fun <E> invoke(elements: List<E>): ThreadSafeList<E>
        {
            return ThreadSafeList(elements.toMutableList())
        }
    }
}


fun main()
{
    // this is how you call it
    val list = listOf("Hello", "World", "!")
    val threadSafeList = threadSafeListOf(list)
}

我在这里所做的可能是一种 hack,但它就像一个魅力。这就是我喜欢科特林的原因。

您可以像往常一样创建对象,在创建对象时也不需要输入 in invoke fun,因为它是 auto-done 由 kotlin 编译器向其传递列表时 auto-done。