Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Map : mapOf()

mapOf() is a function in Kotlin that lets you create an immutable map (a collection that holds key-value pairs). Once a map is created with mapOf(), you cannot add or remove items from it.

Let's explore how to use mapOf() with examples and explanations:

Basic Usage:

val capitals = mapOf("Germany" to "Berlin", "France" to "Paris", "UK" to "London")
println(capitals)  // prints {Germany=Berlin, France=Paris, UK=London}

Features:

  1. Immutable: The map returned by mapOf() is read-only. You cannot modify it after creation.

    // This will result in a compile error
    // capitals["USA"] = "Washington"
    
  2. Nullable and Non-Nullable Values: You can create maps with nullable values or even nullable keys.

    val mapping: Map<String?, String?> = mapOf("apple" to "fruit", null to "nothing", "car" to null)
    println(mapping)  // prints {apple=fruit, null=nothing, car=null}
    
  3. Empty Map: You can create an empty map using mapOf().

    val emptyMap = mapOf<String, String>()
    println(emptyMap.isEmpty())  // prints true
    
  4. Access Elements: You can access the value of a key using the indexing syntax.

    val fruits = mapOf("a" to "apple", "b" to "banana")
    println(fruits["a"])  // prints "apple"
    

Usage with other functions:

Maps in Kotlin can be combined with various collection functions for various operations:

  1. Filtering:

    val numbers = mapOf(1 to "one", 2 to "two", 3 to "three")
    val filtered = numbers.filterKeys { it > 1 }
    println(filtered)  // prints {2=two, 3=three}
    
  2. Mapping:

    val words = mapOf("one" to 1, "two" to 2)
    val mapped = words.mapValues { it.value + 10 }
    println(mapped)  // prints {one=11, two=12}
    
  3. Chaining:

    val results = mapOf(1 to "I", 2 to "II", 3 to "III", 4 to "IV")
                    .filterKeys { it % 2 == 0 }
                    .mapValues { it.value.toLowerCase() }
    println(results)  // prints {2=ii, 4=iv}
    
  4. Fetching keys and values:

    val animals = mapOf("cat" to 4, "spider" to 8)
    val allKeys = animals.keys
    val allValues = animals.values
    println(allKeys)  // prints [cat, spider]
    println(allValues)  // prints [4, 8]
    

In conclusion, mapOf() offers a quick and expressive way to create immutable maps in Kotlin. This immutability provides additional safety by ensuring that the map's contents aren't unexpectedly modified. If you need a mutable map, Kotlin provides the mutableMapOf() function which supports operations like adding, removing, or updating key-value pairs.

  1. Creating a map in Kotlin with mapOf():

    • Maps can be created using the mapOf() function.
    val agesMap = mapOf("Alice" to 25, "Bob" to 30, "Charlie" to 28)
    
  2. Immutable maps in Kotlin:

    • Maps created with mapOf() are immutable, meaning their size and entries cannot be changed.
    // This would result in a compilation error
    agesMap["David"] = 22
    
  3. Initializing and declaring maps with mapOf() in Kotlin:

    • Maps can be initialized and declared using mapOf() in a single line.
    val fruitsMap = mapOf(1 to "Apple", 2 to "Banana", 3 to "Orange")
    
  4. Adding and removing entries in a Kotlin map:

    • As mapOf() creates immutable maps, entries cannot be added or removed.
    // Attempting to add or remove entries would result in a compilation error
    
  5. Accessing values in a map created with mapOf():

    • Values can be accessed using keys.
    val aliceAge = agesMap["Alice"]
    
  6. Iterating over a map in Kotlin:

    • Various loop constructs or collection functions can be used for iteration.
    for ((name, age) in agesMap) {
        // Process each entry
    }
    
  7. Filtering and mapping with mapOf() in Kotlin:

    • Functions like filterKeys, filterValues, and mapValues can be used for data transformations.
    val adultsMap = agesMap.filterValues { it >= 18 }
    val squaredAges = agesMap.mapValues { (_, age) -> age * age }
    
  8. Map functions and methods in Kotlin:

    • Maps offer various functions and methods for common operations.
    val size = agesMap.size
    val keys = agesMap.keys
    
  9. Null safety and mapOf() in Kotlin:

    • Maps can hold nullable types, and null safety principles apply.
    val nullableMap: Map<String, Int?> = mapOf("Alice" to null, "Bob" to 30)
    
  10. mapOf() vs mutableMapOf() in Kotlin:

    • mapOf() creates immutable maps, while mutableMapOf() creates mutable maps.
    val mutableMap = mutableMapOf("Alice" to 25, "Bob" to 30)
    mutableMap["Charlie"] = 28  // Works fine
    
  11. Using mapOf() with different key-value types in Kotlin:

    • mapOf() can be used with various key and value types within the same map.
    val mixedMap = mapOf("Alice" to 25, 2 to "Banana", true to "Orange")
    
  12. Copying and transforming maps in Kotlin:

    • Maps can be copied or transformed using functions like toMap() and toMutableMap().
    val copyMap = agesMap.toMap()
    val mutableCopyMap = agesMap.toMutableMap()