Sling Academy
Home/Kotlin/Using Default Values with `getOrDefault` in Kotlin

Using Default Values with `getOrDefault` in Kotlin

Last updated: December 05, 2024

Kotlin, as a modern programming language, provides many functions that simplify operations developers perform frequently. One such utility is the getOrDefault function available on the Map interface. This function provides a clean and efficient way to manage default values when fetching values from a map if the specified key is absent.

Understanding the getOrDefault Function

The getOrDefault function is particularly useful when you need a fallback value for situations where a key doesn't exist in the map. Normally, when attempting to access a map through a nonexistent key, Kotlin returns a null value. This behavior might not always be desirable, especially when we want operations to proceed with a configurable default value.

The method signature is straightforward:

fun <K, V> Map<out K, V>.getOrDefault(key: K, defaultValue: V): V

This function will return the value associated with the specified key or, if the key doesn't exist, it will return the defaultValue provided.

Example Usage

Let’s look at a practical example to illustrate how getOrDefault can be used in a Kotlin program:

fun main() {
    val fruitsMap = mapOf(
        "apple" to 50,
        "banana" to 30,
        "orange" to 40
    )

    // Existing key
    val applePrice = fruitsMap.getOrDefault("apple", 0)
    println("Apple price: $$applePrice") // Output: Apple price: $50
    
    // Non-existent key
    val kiwiPrice = fruitsMap.getOrDefault("kiwi", 0)
    println("Kiwi price: $$kiwiPrice") // Output: Kiwi price: $0
}

In the example above, the map fruitsMap contains prices of certain fruits. Using getOrDefault, it gracefully handles absent keys, returning a default value of 0 if the corresponding key does not exist, such as in the case of kiwi.

Advantages of using getOrDefault

The getOrDefault function offers several advantages, especially in coding environments where robustness and readability matter:

  • Simplicity: It provides a very straightforward way to handle default values without complex conditional logic.
  • Readability: Code using getOrDefault is often easier to read and understand compared to using neater inline conditional checks.
  • Null Safety: Mitigates the risk of NullPointerException which is a common bug in applications handling missing keys.

Side Note: Mutability Consideration

Note that the getOrDefault function works on both mutable and immutable maps. However, when working with MutableMap, if you also want to add the default value to the map if the key doesn’t exist, consider using getOrPut, which provides this additional functionality:

val scores = mutableMapOf(
    "Anna" to 90,
    "Tom" to 85
)

val johnScore = scores.getOrPut("John") { 75 }
println(scores) // Output: {Anna=90, Tom=85, John=75}

In this case, getOrPut not only fetches a default value but also inserts it into the map if the key isn’t present, helping to maintain application state as needed.

Conclusion

Using getOrDefault in Kotlin is a simple yet powerful feature for developers, eliminating unnecessary null checks and conditions when handling maps. Its integration into Kotlin's API makes handling maps more seamless, enhancing the overall coding experience. As part of Kotlin's collection operations, it undoubtedly contributes to writing cleaner and more efficient Kotlin code.

Next Article: Checking if a Map Contains a Key or Value in Kotlin

Previous Article: Accessing Values by Key in a Map in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin