从地图查找时,有没有办法使函数不 return null

is there a way to make a function to not return null when lookup from a map

有一个 Map<K, V>,需要按键查找并将结果传递给 SDK 的 api,它只接受空值。喜欢:

fun doSomeThing(value: V)

查找可能是

val v = theMap[key]

但是 v 现在可以为 null,即使这里使用的键保证存在并且 v 不会为 null。

有没有办法让函数 return 不可为 null,以防需要从地图中查找?

fun returnNotNullable(key: K): V {
   check(keyExist())
   return theMap[key]!!  // dont like the !! here
}

只是不想像 doSomeThing(theMap[key]!!)

一样使用 !!

?: throw IllegalStateException("Item not found") 而不是 doublebang。 T? ?: throw ... 的类型将是不可空的 T.

您可以使用myMap.getValue(key)