Part 06 / Topic 4 of 7
Maps: key-value pairs
A Map stores values under keys. to is an infix function that builds a Pair — "Rice" to 68.0
is exactly Pair("Rice", 68.0), just easier to read in a builder call:
val catalog = mapOf(
"Rice (kg)" to 68.0,
"Toor dal (kg)" to 145.0,
"Atta (kg)" to 52.0
)
println("Catalog: $catalog")
Catalog: {Rice (kg)=68.0, Toor dal (kg)=145.0, Atta (kg)=52.0}
[key] looks a value up. A missing key gives null, not an exception — plan for it the Part 3 way,
with ?: or getOrDefault, never !!:
println("Price of Rice (kg): ${catalog["Rice (kg)"]}")
println("Price of Sugar (kg): ${catalog["Sugar (kg)"]}")
println("Price of Sugar (kg), with a default: ${catalog["Sugar (kg)"] ?: 0.0}")
println("Same thing via getOrDefault: ${catalog.getOrDefault("Sugar (kg)", 0.0)}")
Price of Rice (kg): 68.0
Price of Sugar (kg): null
Price of Sugar (kg), with a default: 0.0
Same thing via getOrDefault: 0.0
for ((key, value) in map) destructures each entry straight into two names — no separate
.keys/.values juggling needed for the common case of wanting both at once:
for ((item, price) in catalog) {
println("$item -> ₹$price")
}
Rice (kg) -> ₹68.0
Toor dal (kg) -> ₹145.0
Atta (kg) -> ₹52.0
mutableMapOf(...) adds direct assignment and remove(). Updating an existing key by reading its
current value first is the standard pattern for "add to what's already there":
val cart = mutableMapOf("Rice (kg)" to 2, "Toor dal (kg)" to 1)
cart["Atta (kg)"] = 3 // add a new key
cart["Rice (kg)"] = (cart["Rice (kg)"] ?: 0) + 1 // update an existing key
println("Cart: $cart")
cart.remove("Toor dal (kg)")
println("Cart after removing dal: $cart")
Cart: {Rice (kg)=3, Toor dal (kg)=1, Atta (kg)=3}
Cart after removing dal: {Rice (kg)=3, Atta (kg)=3}
🔍 Going deeper:
mapOf/mutableMapOf(andsetOf/mutableSetOf) keep insertion order on the JVM. This was checked, not assumed: printingcatalog.javaClassshowsjava.util.LinkedHashMap, notjava.util.HashMap— Kotlin's default builders already use the ordered JDK types underneath. Only the explicithashMapOf(...)builder opts into plainjava.util.HashMap, whose iteration order is unspecified; this course sticks tomapOf/mutableMapOf/linkedMapOfso every printed collection in this lesson prints in a defined, reproducible order:val reordered = mapOf("Atta (kg)" to 52.0, "Rice (kg)" to 68.0, "Toor dal (kg)" to 145.0) println("Insertion order is kept: $reordered")Insertion order is kept: {Atta (kg)=52.0, Rice (kg)=68.0, Toor dal (kg)=145.0}
Full program: examples/04_maps.kt.
Done here? The practice set for Part 6 — including the solutions — is on the part page.