Kotlin实例化不可变列表 [英] Kotlin Instantiate Immutable List
问题描述
我已经开始使用Kotlin来替代Java,并且非常喜欢它.但是,如果不返回到Java领域,我一直无法找到解决方案:
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<SomeObject>
,需要将其转换为列表,这样我才能多次遍历它.这是不可变列表的一个明显的应用,因为我需要做的就是多次读取它.我实际上如何将这些数据放在开头的列表中? (我知道这是一个接口,但是我无法在文档中找到它的实现)
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<SomeObject>)
方法将实例化不可变的列表对象?
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<T>
是一个只读列表界面,与
In Kotlin, List<T>
is a read-only list interface, it has no functions for changing the content, unlike MutableList<T>
.
通常,List<T>
实现可能是可变列表(例如ArrayList<T>
),但是如果将其作为List<T>
传递,则不会在不进行强制转换的情况下公开任何变异函数.这样的列表引用称为只读,表示该列表不打算更改.这是通过接口的不变性,它被选为实现不变性的方法用于Kotlin stdlib.
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.
更接近问题的地方,Iterable<T>的> toList()
扩展功能将适合:它返回只读的List<T>
.
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屋!