gpt4 book ai didi

nullable - Kotlin mutableMap.put 返回可为空

转载 作者:行者123 更新时间:2023-12-04 18:24:59 44 4
gpt4 key购买 nike

在 kotlin 标准库中我们有 MutableMap 接口(interface)有这个方法

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

如果它接受不可为空的值,为什么返回可空值?是为java互操作做的吗?

最佳答案

看一下定义

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

关于nullable - Kotlin mutableMap.put 返回可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35910429/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com