【发布时间】:2018-11-11 21:47:45
【问题描述】:
我有一个可变列表的自定义 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块中,它调用了mutableList的getter方法。 有没有办法调用 mutabbleList 本身而不是 getter 方法?
【问题讨论】:
-
这是完整的代码吗?由于该属性是私有的,因此拥有一个不可变列表是没有意义的,它根本无法访问。您还必须考虑到您还拥有
list属性,因此使用工厂实现该类可能是值得的。
标签: kotlin