Kotlin 实例化不可变列表 [英] Kotlin Instantiate Immutable List
问题描述
我已经开始使用 Kotlin 作为 Java 的替代品并且非常喜欢它.但是,如果不跳回 java-land,我一直无法找到解决方案:
I've started using Kotlin as a substitute for java and quite like it. However, I've been unable to find a solution to this without jumping back into java-land:
我有一个 Iterable
并且需要将它转换为一个列表,以便我可以多次迭代它.这是一个不可变列表的明显应用,因为我需要做的就是多次阅读它.但是,我如何在开始时将该数据实际放入列表中?(我知道它是一个接口,但我一直无法在文档中找到它的实现)
I have an Iterable<SomeObject>
and need to convert it to a list so I can iterate through it more than once. This is an obvious application of an immutable list, as all I need to do is read it several times. How do I actually put that data in the list at the beginning though? (I know it's an interface, but I've been unable to find an implementation of it in documentation)
可能的(如果不满意)解决方案:
Possible (if unsatisfactory) solutions:
val valueList = arrayListOf(values)
// iterate through valuelist
或
fun copyIterableToList(values: Iterable<SomeObject>) : List<SomeObject> {
var outList = ArrayList<SomeObject>()
for (value in values) {
outList.add(value)
}
return outList
}
除非我误解了,否则这些最终会得到 MutableLists
,它可以工作但感觉像是一种解决方法.是否有类似的 immutableListOf(Iterable
方法可以实例化一个不可变的列表对象?
Unless I'm misunderstanding, these end up with MutableLists
, which works but feels like a workaround. Is there a similar immutableListOf(Iterable<SomeObject>)
method that will instantiate an immutable list object?
推荐答案
在 Kotlin 中,List
是一个只读列表界面,它没有改变内容的功能,不像MutableList
.
In Kotlin, List<T>
is a read-only list interface, it has no functions for changing the content, unlike MutableList<T>
.
一般来说,List
实现可能是一个可变列表(例如ArrayList
),但是如果你传递它作为 List
,不进行强制转换就不会暴露任何变异函数.这种列表引用称为只读,表明该列表不打算更改.这是通过接口的不变性,它被选为不变性的方法用于 Kotlin 标准库.
In general, List<T>
implementation may be a mutable list (e.g. ArrayList<T>
), but if you pass it as a List<T>
, no mutating functions will be exposed without casting. Such a list reference is called read-only, stating that the list is not meant to be changed. This is immutability through interfaces which was chosen as the approach to immutability for Kotlin stdlib.
更接近问题,toList()
stdlib 中 Iterable
的扩展函数将适合:它返回只读 List
.
Closer to the question, toList()
extension function for Iterable<T>
in stdlib will fit: it returns read-only List<T>
.
示例:
val iterable: Iterable<Int> = listOf(1, 2, 3)
val list: List<Int> = iterable.toList()
这篇关于Kotlin 实例化不可变列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!