Dictionary 为什么mutableMapOf返回null?

Dictionary 为什么mutableMapOf返回null?,dictionary,kotlin,nullable,Dictionary,Kotlin,Nullable,我编写了一个简单的代码块,用id在Map中存储片段。map的值和键初始化为不可为空,但当我想将它们作为键和值获取时,它会提供可为空的类型数据。我不明白为什么?在Kotlin中是否有任何其他类型的映射返回不可为空的数据 键[position]可能没有值,这将使其返回null: 返回与给定键对应的值,如果映射中不存在这样的键,则返回null @nhaarman是对的,但是您可以使用getValue(key)返回非null值,但如果找不到则抛出NoSuchElementException /** *

我编写了一个简单的代码块,用
id
Map
中存储
片段。map的
初始化为不可为空,但当我想将它们作为
获取时,它会提供
可为空的
类型数据。我不明白为什么?在
Kotlin
中是否有任何其他类型的映射返回
不可为空的
数据


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

返回与给定键对应的值,如果映射中不存在这样的键,则返回null


@nhaarman是对的,但是您可以使用
getValue(key)
返回非null值,但如果找不到则抛出
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)
/**
*返回给定[key]的值,如果映射中没有此类键,则引发异常。
*
*如果映射是由[withDefault]创建的,则使用其“defaultValue”提供程序函数
*而不是抛出异常。
*
*当映射不包含指定键和的值时,@将引发NoSuchElementException
*没有为该映射提供隐式默认值。
*/
@SinceKotlin(“1.1”)
public fun Map.getValue(键:K):V=getOrImplicitDefault(键)

在你回答之前,我写了以下内容:override fun getItem(position:Int):Fragment=(fragmentsAndIds[position])?:抛出NullPointerException()```它做了类似的事情。但你的选择更简洁、更简短。我会用的。谢谢,它也这么做。顺便说一下,您可以编写
override-fun-getItem(position:Int):Fragment=(fragmentsAndIds[position])
将抛出
NullPointerException
如果为null;)
/**
 * 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)