dictionary - 在函数中从 Hashmap 正确返回 Int

标签 dictionary kotlin return-value

我在 Kotlin 中有一个函数,它接收 Int参数并根据公式返回一个值。为了加快速度,我将中间结果存储在 HashMap<Int, Int>

private val calculatedResults = HashMap<Int, Int>()

private fun q2(n: Int): Int {
    if(calculatedResults.containsKey(n)) {
            return calculatedResults[n]
    }

    val q = ...
    calculatedResults[n] = q
    return q
}

我收到了 type mismatch of Int found but Int? required
return calculatedResults[n]

我不知道如何正确地写这个。我有
return calculatedResults[n]!!

但我不确定,如果它有点hacky。

函数的返回类型是否应该是 Int?因为虽然 HashMap可能包含 key n该值可以是 null ?那不是说 HashMap应该是 <Int, Int?> ?

最佳答案

getOrPut将检查 n 的值是否存在.如果该值存在,它将被返回。如果值不存在,则 lambda 返回的值将被赋值,然后由 getOrPut 返回.

看看这个例子:

fun calculate(n: Int) = n * 5 // some calculation

private fun q2(n: Int) = calculatedResults.getOrPut(n) {
    calculate(n)
}

Should the return type of the function be Int? because while the HashMap might contain the key n the value could be null? Wouldn't that mean the HashMap should be ?



在这种情况下,问题的答案显然是“否”,因为如果缺少该值,您只需添加它。所以,q2 返回的值永远不可能null .

关于dictionary - 在函数中从 Hashmap 正确返回 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100370/

相关文章:

python - python 3中嵌套字典的排序列表

如果没有 @Provides-annotated 方法,就无法提供 android.content.Context

multithreading - 多线程处理70个类似的命令并从每个命令接收输出

Mysql 使用空表返回一些用户选择的值

python - 如何高效地将查询结果展开到字典中

arrays - 在 Python 3 中创建排行榜,排行榜必须从高到低排序

javascript - 使用柏林噪声制作 map ?

kotlin - 从列表中收集偶数到奇数元素以在 Kotlin 中进行映射的惯用方法

kotlin - 后端 (JVM) 内部错误。为什么我会收到此 IDE 错误,而其他具有相同代码的人却不会?

jquery - 从 jquery ajax 调用返回