问题描述
我有一个用于可变列表的自定义getter方法,可以通过使用Google的Guava库返回一个固定的列表.然后在构造函数中访问此可变列表.
I have a custom getter method for a mutable list to return an immtuable list by using Google's Guava library. And then this mutable list is accessed in the constructor.
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块中,它调用mutableList的getter方法.有没有一种方法可以调用mutabbleList本身而不是getter方法?
And I decompile it to Java, in the init block, it calls the getter method of mutableList.Is there a way to call the mutabbleList itself instead of getter method?
推荐答案
当然,它会调用getter(返回ImmutableList.copyOf(field)
).
Of course it calls the getter (which returns ImmutableList.copyOf(field)
).
您可以在init
块中简单地分配给mutableList
新复制的可变列表:
You can do simply assignment to mutableList
new copied mutable list in your init
block:
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获取不可变列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!