为什么mutableMapOf返回空值?

我写了一个简单的代码块来在Map存储带有ids fragments 。 map的valuekey被初始化为非空value ,但是当我想把它们作为keyvalue ,它给出nullablenullable类型数据。 所以,我不明白为什么? 有没有其他类型的地图返回Kotlin non-nullable数据?

在这里输入图像描述

key [position]可能没有值,这会使其返回null

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

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

@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)