Introduction

Welcome to our Kotlin data structures revision! Today, we will delve deeply into Kotlin Maps. Just like a library card catalog, maps enable you to quickly locate the information you need by referring to a label (key). They are vital in Kotlin for efficiently accessing values using keys, as well as for key insertion and deletion. Let's explore Kotlin's Map and MutableMap for a clearer understanding of these concepts.

Kotlin Maps

Maps in Kotlin are a type of data structure that hold data as key-value pairs. They provide an efficient way to store and retrieve information based on unique keys. Each key in a map is associated with exactly one value. You can think of a map like a dictionary where you look up a word (key) to get its definition (value). Keys are unique, but values don't have to be.

Maps can be either mutable or immutable in Kotlin. Immutable maps are read-only, meaning you cannot add, remove, or modify entries once they're created. Mutable maps allow for dynamic changes, such as adding, updating, and removing key-value pairs, making them highly flexible for situations where the dataset needs to be manipulated frequently.

Here's a small example of an immutable map:

val countryCodes: Map<String, String> = mapOf("US" to "United States", "CA" to "Canada")

fun main(){
    println(countryCodes["US"]) // Output: "United States"
    println(countryCodes["CA"]) // Output: "Canada"

    // Since this is a read-only map, you cannot add, remove, or modify entries.
    }

Now, let's look at an example of a PhoneBook class using a MutableMap to store contacts, allowing for dynamic changes:

class PhoneBook {

    private val contacts: MutableMap<String, String> = mutableMapOf()

    fun addContact(name: String, phoneNumber: String) {
        contacts[name] = phoneNumber
    }

    fun getPhoneNumber(name: String): String? {
        return contacts[name]
    }

    fun hasContact(name: String): Boolean {
        return contacts.containsKey(name)
    }

    fun showContact(name: String): String {
        return contacts.get(name) ?: "Contact not found"
    }
}


fun main() {
    // Create a PhoneBook instance
    val phoneBook = PhoneBook()

    // Add contacts
    phoneBook.addContact("Alice", "123-456-7890")
    phoneBook.addContact("Bob", "234-567-8901")

    // Check if contacts exist
    println(phoneBook.hasContact("Alice")) // Output: true
    println(phoneBook.hasContact("Charlie")) // Output: false

    // Retrieve phone numbers
    println(phoneBook.showContact("Alice")) // Output: "123-456-7890"
    println(phoneBook.showContact("Charlie")) // Output: "Contact not found"
}

Explanation

  1. private val contacts: MutableMap<String, String>: This declares a MutableMap to store contact names (keys) and their corresponding phone numbers (values). As a mutable map, it allows for adding, updating, and removing entries.

  2. addContact(name: String, phoneNumber: String):

    • Adds or updates a contact in the contacts map.
    • If a contact with the given name already exists, their phone number is updated. Otherwise, a new key-value pair is added.
  3. getPhoneNumber(name: String): String?:

    • Retrieves the phone number for a given contact name.
    • If the contact is not found, it returns null.
  4. hasContact(name: String): Boolean:

    • Uses containsKey to check if the contact name exists in the contacts map.
    • Returns true if the contact exists, otherwise false.
  5. showContact(name: String): String:

    • Uses the get method to retrieve a contact's phone number.
    • Leverages the Elvis operator to return "Contact not found" if the contact does not exist.
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