Can we cast collection to List?
Collections overviewThe Kotlin Standard Library provides a comprehensive set of tools for managing collections groups of a variable number of items (possibly zero) that are significant to the problem being solved and are commonly operated on. Collections are a common concept for most programming languages, so if you're familiar with, for example, Java or Python collections, you can skip this introduction and proceed to the detailed sections. A collection usually contains a number of objects (this number may also be zero) of the same type. Objects in a collection are called elements or items. For example, all the students in a department form a collection that can be used to calculate their average age. The following collection types are relevant for Kotlin:
Kotlin lets you manipulate collections independently of the exact type of objects stored in them. In other words, you add a String to a list of Strings the same way as you would do with Ints or a user-defined class. So, the Kotlin Standard Library offers generic interfaces, classes, and functions for creating, populating, and managing collections of any type. The collection interfaces and related functions are located in the kotlin.collections package. Let's get an overview of its contents. Collection typesThe Kotlin Standard Library provides implementations for basic collection types: sets, lists, and maps. A pair of interfaces represent each collection type:
Note that altering a mutable collection doesn't require it to be a var: write operations modify the same mutable collection object, so the reference doesn't change. Although, if you try to reassign a val collection, you'll get a compilation error. fun main() { //sampleStart val numbers = mutableListOf("one", "two", "three", "four") numbers.add("five") // this is OK println(numbers) //numbers = mutableListOf("six", "seven") // compilation error //sampleEnd } The read-only collection types are covariant. This means that, if a Rectangle class inherits from Shape, you can use a List In turn, mutable collections aren't covariant; otherwise, this would lead to runtime failures. If MutableList Below is a diagram of the Kotlin collection interfaces: Let's walk through the interfaces and their implementations. To learn about Collection, read the section below. To learn about List, Set, and Map, you can either read the corresponding sections or watch a video by Sebastian Aigner, Kotlin Developer Advocate: CollectionCollection fun printAll(strings: Collection MutableCollection fun List ListList fun main() { //sampleStart val numbers = listOf("one", "two", "three", "four") println("Number of elements: ${numbers.size}") println("Third element: ${numbers.get(2)}") println("Fourth element: ${numbers[3]}") println("Index of element \"two\" ${numbers.indexOf("two")}") //sampleEnd } List elements (including nulls) can duplicate: a list can contain any number of equal objects or occurrences of a single object. Two lists are considered equal if they have the same sizes and structurally equal elements at the same positions. data class Person(var name: String, var age: Int) fun main() { //sampleStart val bob = Person("Bob", 31) val people = listOf(Person("Adam", 20), bob, bob) val people2 = listOf(Person("Adam", 20), Person("Bob", 31), bob) println(people == people2) bob.age = 32 println(people == people2) //sampleEnd } MutableList fun main() { //sampleStart val numbers = mutableListOf(1, 2, 3, 4) numbers.add(5) numbers.removeAt(1) numbers[0] = 0 numbers.shuffle() println(numbers) //sampleEnd } As you see, in some aspects lists are very similar to arrays. However, there is one important difference: an array's size is defined upon initialization and is never changed; in turn, a list doesn't have a predefined size; a list's size can be changed as a result of write operations: adding, updating, or removing elements. In Kotlin, the default implementation of List is ArrayList which you can think of as a resizable array. SetSet fun main() { //sampleStart val numbers = setOf(1, 2, 3, 4) println("Number of elements: ${numbers.size}") if (numbers.contains(1)) println("1 is in the set") val numbersBackwards = setOf(4, 3, 2, 1) println("The sets are equal: ${numbers == numbersBackwards}") //sampleEnd } MutableSet is a Set with write operations from MutableCollection. The default implementation of Set LinkedHashSet preserves the order of elements insertion. Hence, the functions that rely on the order, such as first() or last(), return predictable results on such sets. fun main() { //sampleStart val numbers = setOf(1, 2, 3, 4) // LinkedHashSet is the default implementation val numbersBackwards = setOf(4, 3, 2, 1) println(numbers.first() == numbersBackwards.first()) println(numbers.first() == numbersBackwards.last()) //sampleEnd } An alternative implementation HashSet says nothing about the elements order, so calling such functions on it returns unpredictable results. However, HashSet requires less memory to store the same number of elements. MapMap fun main() { //sampleStart val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1) println("All keys: ${numbersMap.keys}") println("All values: ${numbersMap.values}") if ("key2" in numbersMap) println("Value by key \"key2\": ${numbersMap["key2"]}") if (1 in numbersMap.values) println("The value 1 is in the map") if (numbersMap.containsValue(1)) println("The value 1 is in the map") // same as previous //sampleEnd } Two maps containing the equal pairs are equal regardless of the pair order. fun main() { //sampleStart val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1) val anotherMap = mapOf("key2" to 2, "key1" to 1, "key4" to 1, "key3" to 3) println("The maps are equal: ${numbersMap == anotherMap}") //sampleEnd } MutableMap is a Map with map write operations, for example, you can add a new key-value pair or update the value associated with the given key. fun main() { //sampleStart val numbersMap = mutableMapOf("one" to 1, "two" to 2) numbersMap.put("three", 3) numbersMap["one"] = 11 println(numbersMap) //sampleEnd } The default implementation of Map LinkedHashMap preserves the order of elements insertion when iterating the map. In turn, an alternative implementation HashMap says nothing about the elements order. Last modified: 10 December 2021 Kotlin roadmap Constructing collections
|