kotlin - 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]!!)
解决方案
Do ?: throw IllegalStateException("Item not found")
instead of doublebang. The type of T? ?: throw ...
will be non-nullable T
.
推荐阅读
- sql - 如何使用 ST_Touches 获取触摸几何的相交长度
- shell - 如何在 zsh 脚本中编写复杂的 psql 命令?
- c# - 使用 IronWebScraper 时如果一个 URL 返回 404,如何继续抓取下一个 URL
- python - 使用现有变量引用 pandas 列名
- functional-programming - 带有延续问题的 F# 扩展欧几里得算法
- r - 在 R 中生成随机块示意图
- angular - 如何获取
标记动态值并使用 Angular 2 将其传递给打字稿
- python - 将鼠标光标移动到从文本文件导入的坐标
- reactjs - ReactJs MaterialUi onRowUpdate 字段验证
- redirect - IIS 重定向规则将一个 url 重定向到另一个