Basic Usage
Creating collections is nice, but eventually, we need to get data in and out of them and otherwise manipulate them.
[]
Syntax
To retrieve values from a collection (other than a Set
), you can use []
. For arrays and lists, the value passed into the []
operator is the 0
-based index into the collection. For maps, the value passed into the []
operator is the key for which you wish to look up the corresponding value.
val thingsArray = arrayOf("foo", "bar", "goo")
println(thingsArray[0])
val thingsIntArray = intArrayOf(1, 3, 3, 7)
println(thingsIntArray[1])
val thingsList = listOf("foo", "bar", "goo")
println(thingsList[2])
val thingsMap = mapOf("key" to "value", "other-key" to "other-value")
println(thingsMap["other-key"])
Running this in the Klassbook will give you:
foo
3
goo
other-value
Things get a bit interesting if we start playing with that map of the lists of odd and even single-digit integers:
val oddEven = mapOf("odd" to listOf(1, 3, 5, 7, 9), "even" to listOf(2, 4, 6, 8))
println(oddEven["odd"].size)
This will fail to run, with a compile error:
error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type List<Int>?
A Map
may return null
for a given key, as there may not be a value for that key. As it turns out, our Map
has a value for the odd
key, and so at runtime, this would succeed. And in most programming languages, we could actually compile and run this sort of operation. This fails in Kotlin, because of how Kotlin handles the possibility of null
as a value. We will explore this in much greater detail later in the book.
Typical Stuff
If you are used to working with collections in other programming languages, it will come as little surprise that Kotlin has a lot of the same basic functions for working with its collections.
In addition to the size
property, you will have things like:
-
isEmpty()
, for a quickBoolean
value based on whether the collection is empty -
contains()
, which will returntrue
if the collection contains the requested item (for maps, this checks the keys — usecontainsValue()
to check the values)
For lists and arrays, you have things like:
-
first()
, to get the first element -
last()
, to get the last element -
firstOrNull()
, to get the first element ornull
if the collection is empty - And so on
Conversion Functions
The one-dimensional collection types (arrays, lists, sets) have a rich set of conversion functions to migrate between types:
-
Array
offerstoList()
andtoSet()
-
List
offerstoSet()
andtoTypedArray()
-
Set
offerstoList()
andtoTypedArray()
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.