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.
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:
Now, let's look at an example of a PhoneBook class using a MutableMap to store contacts, allowing for dynamic changes:
Explanation
-
private val contacts: MutableMap<String, String>: This declares aMutableMapto store contact names (keys) and their corresponding phone numbers (values). As a mutable map, it allows for adding, updating, and removing entries. -
addContact(name: String, phoneNumber: String):- Adds or updates a contact in the
contactsmap. - If a contact with the given name already exists, their phone number is updated. Otherwise, a new key-value pair is added.
- Adds or updates a contact in the
-
getPhoneNumber(name: String): String?:- Retrieves the phone number for a given contact name.
- If the contact is not found, it returns
null.
-
hasContact(name: String): Boolean:- Uses
containsKeyto check if the contact name exists in thecontactsmap. - Returns
trueif the contact exists, otherwisefalse.
- Uses
-
showContact(name: String): String:- Uses the
getmethod to retrieve a contact's phone number. - Leverages the Elvis operator to return "Contact not found" if the contact does not exist.
- Uses the
