Kotlin mutableMap.put返回可空

时间:2016-03-10 07:44:13

标签: nullable kotlin

在kotlin标准库中,我们有MutableMap接口 有这种方法

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

如果它接受不可为空的值,为什么它会返回可空值?它是为java interop完成的吗?

1 个答案:

答案 0 :(得分:7)

看一下定义

/**
 * 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?

所以

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")
}

打印:

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