All non-Mutable____
collections in Kotlin are compile time read-only types by default, but not immutable. See the following code snippet:
fun main(args: Array<String>) {
// Explanation for ArrayList(listOf()) later down the post
val list: List<Int> = ArrayList(listOf(1, 2, 3))
println(list) // [1, 2, 3]
// Fails at compile time
// list.add(4)
// Uh oh! This works at runtime!
(list as MutableList<Int>).add(4)
println(list) // [1, 2, 3, 4]
}
要想有一个不变的列表,请考虑番石榴的Immutable____
个集合:
import com.google.common.collect.ImmutableList
fun main(args: Array<String>) {
val list: List<Int> = ImmutableList.of(1, 2, 3)
println(list) // [1, 2, 3]
// Fails at compile time
// list.add(4)
// Fails at runtime, as expected
(list as MutableList<Int>).add(4)
println(list) // [1, 2, 3, 4]
}
请注意,Kotlin的一些标准运行时函数可能返回不可修改、不可调整大小等的集合,因此当您将只读集合直接强制转换为可变集合时,所有赌注都会失效.
For example, listOf()
currently (this may change in the future!) returns a java.util.Arrays.ArrayList
around the array of vararg parameters via Arrays.asList(T...)
. This "list" can be modified, but elements can never be added or removed, as you cannot resize an array. See Arrays.asList(T...)
javadoc for more information.
If you really want a mutable collection from any given collection, consider making a copy using .toMutableList()
. This will work on any collection:
import com.google.common.collect.ImmutableList
fun main(args: Array<String>) {
val list: List<Int> = ImmutableList.of(1, 2, 3)
val copy = list.toMutableList()
copy.add(4)
println(copy) // [1, 2, 3, 4]
println(list) // [1, 2, 3]
}