我在 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/