0
0
KotlinHow-ToBeginner · 3 min read

How to Get Value from Map in Kotlin: Simple Guide

In Kotlin, you get a value from a Map by using the key inside square brackets like map[key] or by calling map.get(key). If the key is not found, these return null unless you use getValue(key) which throws an exception if the key is missing.
📐

Syntax

To get a value from a Map in Kotlin, you can use:

  • map[key]: Returns the value for the key or null if not found.
  • map.get(key): Same as map[key], returns value or null.
  • map.getValue(key): Returns the value or throws an exception if the key is missing.
kotlin
val map = mapOf("apple" to 1, "banana" to 2)
val value1 = map["apple"]
val value2 = map.get("banana")
val value3 = map.getValue("apple")
Output
value1 = 1 value2 = 2 value3 = 1
💻

Example

This example shows how to get values safely from a map and handle missing keys.

kotlin
fun main() {
    val fruits = mapOf("apple" to 10, "banana" to 20)

    // Using [] operator
    val appleCount = fruits["apple"]
    println("Apple count: $appleCount")

    // Using get() method
    val bananaCount = fruits.get("banana")
    println("Banana count: $bananaCount")

    // Using getValue() method (throws if key missing)
    try {
        val orangeCount = fruits.getValue("orange")
        println("Orange count: $orangeCount")
    } catch (e: NoSuchElementException) {
        println("Key 'orange' not found in map")
    }
}
Output
Apple count: 10 Banana count: 20 Key 'orange' not found in map
⚠️

Common Pitfalls

Common mistakes when getting values from a map include:

  • Assuming map[key] never returns null. It returns null if the key is missing.
  • Using getValue(key) without handling exceptions, which crashes if the key is absent.
  • Not checking for null when using map[key] or get(key).
kotlin
val map = mapOf("a" to 1)

// Wrong: may cause NullPointerException
// val value = map["b"]!!

// Right: safe check
val value = map["b"] ?: 0
📊

Quick Reference

Summary of methods to get values from a Kotlin map:

MethodReturnsBehavior if key missing
map[key]Value or nullReturns null
map.get(key)Value or nullReturns null
map.getValue(key)ValueThrows exception

Key Takeaways

Use map[key] or map.get(key) to get values safely, which return null if key is missing.
Use map.getValue(key) only if you want an exception when the key is missing.
Always check for null when using map[key] to avoid crashes.
Handle exceptions when using getValue(key) to prevent program errors.
Remember that Kotlin maps are immutable by default; use mutableMapOf for changes.