为什么mutableMapOf返回可空?

时间:2017-08-09 10:26:45

标签: dictionary kotlin nullable

我写了一个简单的代码块,用fragmentsids中存储Map。地图的valuekey初始化为非可空,但当我想将其设为keyvalue时,会提供nullable类型数据。所以,我不明白为什么?是否有其他类型的地图会在non-nullable中返回Kotlin数据?

enter image description here

2 个答案:

答案 0 :(得分:9)

键[position]可能没有值,这将使其返回null

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

返回与给定键对应的值,如果地图中不存在此键,则返回null。

答案 1 :(得分: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)