Kotlin Instantiate Immutable List

[亡魂溺海] 提交于 2019-11-27 07:08:36

问题


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:

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

or

fun copyIterableToList(values: Iterable<SomeObject>) : List<SomeObject> {
    var outList = ArrayList<SomeObject>()
    for (value in values) {
        outList.add(value)
    }
    return outList
}

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?


回答1:


In Kotlin, List<T> is a read-only list interface, it has no functions for changing the content, unlike MutableList<T>.

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.

Closer to the question, toList() extension function for Iterable<T> in stdlib will fit: it returns read-only List<T>.

Example:

val iterable: Iterable<Int> = listOf(1, 2, 3)
val list: List<Int> = iterable.toList()


来源:https://stackoverflow.com/questions/34770493/kotlin-instantiate-immutable-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!