Kotlin类委托特性

Kotlin类委托特性,kotlin,Kotlin,这就是我如何在Kotlin中创建类委派的方法: class CustomList<T>(private val data: ArrayList<T> = ArrayList<T>()) : List<T> by data 这似乎不起作用 如何使数据成为一个内部字段,并将列表委托给它的方法,而不必编写所有委托方法?目前仅适用于主构造函数的参数 解决方法:将主构造函数声明为私有,并提供一个委托给它的公共构造函数 class CustomList<

这就是我如何在Kotlin中创建类委派的方法:

class CustomList<T>(private val data: ArrayList<T> = ArrayList<T>()) : List<T> by data
这似乎不起作用

如何使
数据
成为一个内部字段,并将列表委托给它的方法,而不必编写所有委托方法?

目前仅适用于主构造函数的参数

解决方法:将主构造函数声明为私有,并提供一个委托给它的公共构造函数

class CustomList<T> private constructor(private val data: List<T>) : List<T> by data {
    constructor() : this(ArrayList())
}
class CustomList私有构造函数(私有val数据:List):按数据列出{
构造函数():此(ArrayList())
}

使用
listOf()
而不是
ArrayList()
。没有必要指定
ArrayList
@Joshua通常您是对的,但是OP的原始代码实例化了
ArrayList()
class CustomList<T> private constructor(private val data: List<T>) : List<T> by data {
    constructor() : this(ArrayList())
}