Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
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:
val capitals = mapOf("Germany" to "Berlin", "France" to "Paris", "UK" to "London") println(capitals) // prints {Germany=Berlin, France=Paris, UK=London}
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"
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}
Empty Map: You can create an empty map using mapOf()
.
val emptyMap = mapOf<String, String>() println(emptyMap.isEmpty()) // prints true
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"
Maps in Kotlin can be combined with various collection functions for various operations:
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}
Mapping:
val words = mapOf("one" to 1, "two" to 2) val mapped = words.mapValues { it.value + 10 } println(mapped) // prints {one=11, two=12}
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}
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.
Creating a map in Kotlin with mapOf()
:
mapOf()
function.val agesMap = mapOf("Alice" to 25, "Bob" to 30, "Charlie" to 28)
Immutable maps in Kotlin:
mapOf()
are immutable, meaning their size and entries cannot be changed.// This would result in a compilation error agesMap["David"] = 22
Initializing and declaring maps with mapOf()
in Kotlin:
mapOf()
in a single line.val fruitsMap = mapOf(1 to "Apple", 2 to "Banana", 3 to "Orange")
Adding and removing entries in a Kotlin map:
mapOf()
creates immutable maps, entries cannot be added or removed.// Attempting to add or remove entries would result in a compilation error
Accessing values in a map created with mapOf()
:
val aliceAge = agesMap["Alice"]
Iterating over a map in Kotlin:
for ((name, age) in agesMap) { // Process each entry }
Filtering and mapping with mapOf()
in Kotlin:
filterKeys
, filterValues
, and mapValues
can be used for data transformations.val adultsMap = agesMap.filterValues { it >= 18 } val squaredAges = agesMap.mapValues { (_, age) -> age * age }
Map functions and methods in Kotlin:
val size = agesMap.size val keys = agesMap.keys
Null safety and mapOf()
in Kotlin:
val nullableMap: Map<String, Int?> = mapOf("Alice" to null, "Bob" to 30)
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
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")
Copying and transforming maps in Kotlin:
toMap()
and toMutableMap()
.val copyMap = agesMap.toMap() val mutableCopyMap = agesMap.toMutableMap()