Topic Overview and Actualization

Greetings, student! Today, we're studying the Map data structure in Kotlin. It functions like a dictionary, pairing a unique key with a corresponding value. Our primary focus will be on creating, accessing, and utilizing the unique properties of Maps in Kotlin.

Understanding Maps in Kotlin

In Kotlin, a Map stores key-value entries. Consider a dictionary, where words are keys, and definitions are values. This analogy parallels a Map's functioning: keys are unique, just as no two words share the same meaning.

fun main() {
   val animalHabitats = mapOf("Lion" to "Savannah", "Penguin" to "Antarctica", "Kangaroo" to "Australia")
   println(animalHabitats) // prints {Lion=Savannah, Penguin=Antarctica, Kangaroo=Australia}
}
Creating and Modifying Maps in Kotlin

In Kotlin, mapOf() and mutableMapOf() are functions designed for creating Maps, collections of key-value pairs. For mutable maps, you can insert or modify a key-value pair using the syntax map[<key>] = <value>. Modifying an existing key updates its associated value.

fun main() {
    val immutableMap = mapOf("Sam" to 23, "Amanda" to 30, "Trevor" to 29)
    println(immutableMap) // prints {Sam=23, Amanda=30, Trevor=29}

    val mutableMap = mutableMapOf("Mary" to 31, "Bob" to 28, "Hannah" to 27)
    mutableMap["Roman"] = 27  // Adding a new key-value pair
    mutableMap["Bob"] = 29 // Bob's age is updated to 29
    println(mutableMap) // prints {Mary=31, Bob=29, Hannah=27, Roman=27}
}

This example demonstrates not only how to define immutable and mutable maps but also how to dynamically add elements to mutable maps and modify existing entries.

Accessing and Modifying Elements in Maps

We access values in Maps via their keys. To add or remove elements, we respectively use the put() and remove() functions.

fun main() {
    val namesToAges = mapOf("Sam" to 23, "Amanda" to 30, "Trevor" to 29)
    println(namesToAges["Amanda"]) // prints 30
    
    val mutableNamesToAges = mutableMapOf("Sam" to 23, "Amanda" to 30)
    mutableNamesToAges.put("Trevor", 29)
    println(mutableNamesToAges) // prints {Sam=23, Amanda=30, Trevor=29}
    
    mutableNamesToAges.remove("Sam")
    println(mutableNamesToAges) // prints {Amanda=30, Trevor=29}
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal