Search code examples
nullablekotlin

Kotlin mutableMap.put returns nullable


In kotlin standard lib we have MutableMap interface which has this method

public abstract fun put(key: K, value: V): V?

Why is it returning nullable value if it accepts not nullable one? Is it done for java interop?


Solution

  • Take a look at the definition

    /**
     * Associates the specified [value] with the specified [key] in the map.
     *
     * @return the previous value associated with the key, or `null` if the key was not present in the map.
     */
    public fun put(key: K, value: V): V?
    

    So

    fun main(args: Array<String>) {
        var m: MutableMap<Int, String> = mutableMapOf(Pair(1, "a"))
        val prev1Value = m.put(1, "b")
        val prev2Value = m.put(2, "c")
    
        println(m)
        println("Previous value of 1 was: $prev1Value")
        println("Previous value of 2 was: $prev2Value")
    }
    

    Prints:

    {1=b, 2=c}
    Previous value of 1 was: a
    Previous value of 2 was: null