2016-03-10 69 views
2

在科特林標準庫,我們有MutableMap接口 擁有這種方法科特林mutableMap.put返回null的

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

爲什麼回國空值,如果它接受不可空嗎?它是爲java interop完成的嗎?

回答

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 
+0

你如何得到這些?在我的設置(kotlin插件)中,我沒有看到任何文檔... – vach

+0

哦,似乎intellij一直在使用反編譯器......會找到如何附上來源 – vach

+0

我使用IntelliJ Idea 15.0.4。只需按住'ctrl'並點擊'放入'功能 – RoninDev