Collections

Kotlin has simple funtions to initialize collections. The following line of code shows an example of initializing a list:

    val countries = listOf("India", "China", "USA")

The following code snippet shows some of the important operations that can be performed on a list:

    println(countries.size)//3
println(countries.first())//India
println(countries.last())//USA
println(countries[2])//USA

Lists, created with listOf, are immutable in Kotlin. To be able to change the content of a list, the mutableListOf function needs to be

    //countries.add("China") //Not allowed
val mutableContries = mutableListOf("India", "China", "USA")
mutableContries.add("China")

The mapOf function is used to initialize a map, as shown in the following code snippet:

    val characterOccurances = 
mapOf("a" to 1, "h" to 1, "p" to 2, "y" to 1)//happy
println(characterOccurances)//{a=1, h=1, p=2, y=1}

The following line of code shows the retrieval of a value for a specific key:

    println(characterOccurances["p"])//2

A map can be destructured into its key value constituents in a loop. The following lines of code show the details:

    for ((key, value) in characterOccurances) {
println("$key -> $value")
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset