我有一个可变列表的自定义 getter 方法,可以使用 Google 的 Guava 库返回不可变列表。然后在构造函数中访问这个可变列表。
data class mutableClass(val list: List<Foo>) {
private val mutableList: MutableList<Foo>
get() = ImmutableList.copyOf(field)
init {
mutableList = mutableListOf()
list.forEach {
mutableList.add(it.copy()) // Exception is thrown here.
// It actually calls its getter method which is an immutable
// list, so when init this class, it throw exception
}
}
}
data class Foo {}
我将它反编译为Java,在init block 中,它调用了mutableList的getter方法。 有没有办法调用 mutabbleList 本身而不是 getter 方法?
最佳答案
当然它会调用 getter(它返回 ImmutableList.copyOf(field)
)。
您可以在 init
block 中简单地分配给 mutableList
新复制的可变列表:
data class MutableClass(val list: List<Foo>) {
private val mutableList: MutableList<Foo>
get() = ImmutableList.copyOf(field)
init {
mutableList = list.map { it.copy() }.toMutableList()
}
}
或者没有init
:
data class MutableClass(val list: List<Foo>) {
private val mutableList: MutableList<Foo> = list.map { it.copy() }.toMutableList()
get() = ImmutableList.copyOf(field)
}
关于kotlin自定义从mutableList获取不可变列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50648717/