英文:
Kotlin get value by key from map
问题
假设我们有一个映射:
val charToCount = mapOf('a', 3)
任务是通过相应的键检索值 3
。问题在于 map.get(...)
返回可空类型 T?
而不是 T
。如果保证键在映射中存在且相应的值 != null
,怎样才是将该值转换为非空类型的最佳实践呢?
从我的理解来看,有两种方法:
val count = charToCount['a']!!
val count = charToCount['a'] ?: error("...")
但是这两种方法都不够简洁。是否有更好的方法来处理可空类型呢?
英文:
Let's assume we have a map:
val charToCount = mapOf('a', 3)
The task is to retrieve the value 3
by the corresponding key. The problem is map.get(...)
returns nullable type T?
instead of T
. What's the best practice to convert the value to non-nullable type if there is a guarantee that the key is present in the map and the corresponding value != null
?
Off the top of my head there are two ways:
val count = charToCount['a']!!
val count = charToCount['a'] ?: error("...")
But both of them don't seem concise. Are there any better approaches to chip away with a nullable type?
答案1
得分: 6
适当的方法是:
val count: Int = charToCount.getValue('a')
这会根据文档“在映射中没有这样的键时抛出异常”。
如果你希望更加简洁,抱歉可能不能比得上 !!
。
英文:
The appropriate method is
val count: Int = charToCount.getValue('a')
...which "throws an exception if there is no such key in the map," according to its docs.
Sorry if you were hoping for something more concise; if you want something short, you can't possibly beat !!
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论