Kotlin数据类中可变集合的防御性副本 [英] Defensive copy of a mutable collection in Kotlin data class
问题描述
我想让一个数据类接受一个只读列表:
I want to have a data class accepting a read-only list:
data class Notebook(val notes: List<String>) {
}
但是它也可以接受MutableList
,因为它是List
的子类型.
But it can accept MutableList
as well, because it is a subtype of the List
.
例如,以下代码修改了传入列表:
For example the following code modifies the passed in list:
fun main(args: Array<String>) {
val notes = arrayListOf("One", "Two")
val notebook = Notebook(notes)
notes.add("Three")
println(notebook) // prints: Notebook(notes=[One, Two, Three])
}
有没有一种方法可以对数据类中的传入列表进行防御性复制?
Is there a way how perform defensive copy of the passed in list in the data class?
推荐答案
我认为最好将JetBrains库用于不可变集合- https://github.com/Kotlin/kotlinx.collections.immutable
I think better is to use JetBrains library for immutable collections - https://github.com/Kotlin/kotlinx.collections.immutable
导入您的项目
添加Bintray存储库:
Add the bintray repository:
repositories {
maven {
url "http://dl.bintray.com/kotlin/kotlinx"
}
}
添加依赖项:
compile 'org.jetbrains.kotlinx:kotlinx-collections-immutable:0.1'
结果:
data class Notebook(val notes: ImmutableList<String>) {}
fun main(args: Array<String>) {
val notes = immutableListOf("One", "Two")
val notebook = Notebook(notes)
notes.add("Three") // creates a new collection
println(notebook) // prints: Notebook(notes=[One, Two])
}
注意: 您还可以在ImmutableList中使用add和remove方法,但是此方法不会修改当前列表,只是使用您的更改创建一个新列表并为您返回.
Note: You also can use add and remove methods with ImmutableList, but this methods doesn't modify current list just creates new one with your changes and return it for you.
这篇关于Kotlin数据类中可变集合的防御性副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!