首页 > 解决方案 > is there a way to make a function to not return null when lookup from a map

问题描述

Having a Map<K, V>, and need to look up by key and pass the result to a SDK's api which takes only on-null value. like:

fun doSomeThing(value: V)

The look up could be as

val v = theMap[key]

but the v is nullable now, even if the key used here is guaranteed to exist and the v will be not null.

is there a way to make function not return nullable in case need to look up from a map?

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

just dont want to use !! like doSomeThing(theMap[key]!!)

标签: kotlinhashmapnullable

解决方案


Do ?: throw IllegalStateException("Item not found") instead of doublebang. The type of T? ?: throw ... will be non-nullable T.


推荐阅读