2017-08-09 143 views
4

我写了一个简单的代码块来存储fragmentsidsMap。地图的valuekey被初始化为非空值,但是当我想让它们为keyvalue时,它给出nullable类型的数据。所以,我不明白为什么?有没有其他类型的地图返回数据Kotlin为什么mutableMapOf返回空值?

enter image description here

回答

9

这是可能的存在是关键[位置]没有价值,这将使其返回null

abstract operator fun get(key: K): V? 

返回对应于给定的密钥,或为空值如果这样的密钥不存在于地图中。

3

@nhaarman是对的,但你可以使用返回非空的getValue(key),但如果没有找到则返回NoSuchElementException

/** 
* Returns the value for the given [key] or throws an exception if there is no such key in the map. 
* 
* If the map was created by [withDefault], resorts to its `defaultValue` provider function 
* instead of throwing an exception. 
* 
* @throws NoSuchElementException when the map doesn't contain a value for the specified key and 
* no implicit default value was provided for that map. 
*/ 
@SinceKotlin("1.1") 
public fun <K, V> Map<K, V>.getValue(key: K): V = getOrImplicitDefault(key) 
+1

在你回答之前,我写了这个。 :'''重写fun getItem(position:Int):Fragment =(fragmentsAndIds [position])?:throw NullPointerException()'''' 它确实类似于此。但是你的选择更加简洁。我会用它。谢谢 – emiraslan

+1

是的,它做同样的事情。顺便说一句,你可以写'重写getItem(position:Int):Fragment =(fragmentsAndIds [position])!!'。如果为空,'!!'会抛出'NullPointerException';) –

相关问题