Kotlin Instantiate Immutable List

前端 未结 1 791
说谎
说谎 2020-12-11 07:55

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 h

相关标签:
1条回答
  • 2020-12-11 08:34

    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()
    
    0 讨论(0)
提交回复
热议问题