如何在Kotlin中创建一个不可变列表,而在Java中它也是一个不可变列表? [英] How to create an immutable list in Kotlin that is also an immutable list in Java?
问题描述
我有一个Java/Kotlin互操作问题. Kotlin不可变列表被编译为可变的普通java.util.ArrayList!
I have a Java/Kotlin interop problem. A Kotlin immutable list is compiled into a normal java.util.ArrayList that is mutable!
科林(图书馆):
class A {
val items: List<Item> = ArrayList()
}
Java(消费者):
Java (consumer):
A a = new A();
a.getItems().add(new Item()); // Compiles and runs but I wish to fail or throw
从Java角度来看,如何也使我的Kotlin类完全不可变?
How to make my Kotlin class fully immutable from Java perspective too?
推荐答案
默认情况下,Kotlin中的所有非Mutable____
集合都是编译时只读类型,但不是不可变的.请参见以下代码段:
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____
集合:
To truly have an immutable list, consider Guava's Immutable____
collections:
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的某些标准运行时函数可能会返回不可修改,不可调整大小的集合,因此,当您直接将只读集合转换为可变集合时,所有押注都会被取消.
Be aware that some of Kotlin's standard runtime function may return collections that are either unmodifiable, not resizable, etc., so all bets are off when you directly cast a read-only collection to a mutable one.
例如,当前listOf()
(将来可能会更改!)会通过Arrays.asList(T...)
在vararg参数数组周围返回java.util.Arrays.ArrayList
.可以修改此列表",但是永远不能添加或删除元素,因为您不能调整数组的大小.参见 Arrays.asList(T...)
javadoc 了解更多信息.
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.
如果您确实想要任何给定集合中的可变集合,请考虑使用.toMutableList()
进行复制.这将适用于任何集合:
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]
}
这篇关于如何在Kotlin中创建一个不可变列表,而在Java中它也是一个不可变列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!