Kotlin 从映射中按键获取值

huangapple go评论83阅读模式
英文:

Kotlin get value by key from map

问题

假设我们有一个映射:

val charToCount = mapOf('a', 3)

任务是通过相应的键检索值 3。问题在于 map.get(...) 返回可空类型 T? 而不是 T。如果保证键在映射中存在且相应的值 != null,怎样才是将该值转换为非空类型的最佳实践呢?

从我的理解来看,有两种方法:

  1. val count = charToCount['a']!!
  2. 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:

  1. val count = charToCount['a']!!
  2. 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 !!.

huangapple
  • 本文由 发表于 2020年8月28日 07:01:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63625231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定