官术网_书友最值得收藏!

  • Functional Kotlin
  • Mario Arias Rivu Chakraborty
  • 298字
  • 2021-06-24 19:15:29

Immutable collections

Kotlin gives preference to immutability wherever possible, but leaves the choice to the developer whether or when to use it. This power of choice makes the language even more powerful. Unlike most languages, where they have either only mutable (like Java, C#, and so on) or only immutable collections (like F#, Haskell, Clojure, and so on), Kotlin has both and distinguishes between them, leaving the developer with the freedom to choose whether to use an immutable or mutable one.

Kotlin has two interfaces for collection objects—Collection<out E> and MutableCollection<out E>; all the collection classes (for example, List, Set, or Map) implement either of them. As the name suggests, the two interfaces are designed to serve immutable and mutable collections respectively. Let us have an example:

fun main(args: Array<String>) { 
    val immutableList = listOf(1,2,3,4,5,6,7)//(1) 
    println("Immutable List $immutableList") 
    val mutableList:MutableList<Int> = immutableList.toMutableList()//(2) 
    println("Mutable List $mutableList") 
    mutableList.add(8)//(3) 
    println("Mutable List after add $mutableList") 
    println("Mutable List after add $immutableList") 
} 

The output is as follows:

So, in this program, we created an immutable list with the help of the listOf method of Kotlin, on comment (1). The listOf method creates an immutable list with the elements (varargs) passed to it. This method also has a generic type parameter, which can be skipped if the elements array is not empty. The listOf method also has a mutable version—mutableListOf() which is identical except that it returns MutableList instead. We can convert an immutable list to a mutable one with the help of the toMutableList() extension function, we did the same in comment (2), to add an element to it on comment (3). However, if you check the output, the original Immutable List remains the same without any changes, the item is, however, added to the newly created MutableList instead.

主站蜘蛛池模板: 绩溪县| 开江县| 西乡县| 怀宁县| 常山县| 油尖旺区| 贵阳市| 许昌县| 芜湖市| 淮安市| 武山县| 黄梅县| 同德县| 广丰县| 武鸣县| 鹿泉市| 江西省| 大城县| 广安市| 南投市| 河间市| 眉山市| 中西区| 深泽县| 酒泉市| 乌拉特中旗| 汕尾市| 绥阳县| 宜黄县| 林西县| 巴林右旗| 柘城县| 庆阳市| 且末县| 鹤山市| 新邵县| 达拉特旗| 绵竹市| 临桂县| 苏州市| 泰州市|