我在Kotlin中使用的是HashMap<Int, Int>
,当I为get
时,返回类型为Int?
.
How can I convert the Int?
to an Int
?
So far I've tried using Int?.toInt()
, but that seems to be returning an Int?
.
I'm writing a Fibonacci function, and my code looks like:
val fibMemo : Map<Int, Int> = HashMap<Int,Int>()
fun fibN(n:Int) : Int {
if (n == 0 || n == 1) return 1
if (fibMemo.containsKey(n))
// Error here: Type mismatch: inferred type is Int? but Int was expected
return fibMemo.get(n)?.toInt()
else {
val newNum : Int = fibN(n-1) + fibN(n-2)
fibMemo.put(n, newNum)
return newNum
}
}