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

推荐答案

The direct answer, use the !! operator to assert that you trust a value is NOT null and therefore changing its type to the non null equivalent. A simple sample showing the assertion allowing the conversion (which applies to any nullable type, not just Int?)

val nullableInt: Int? = 1
val nonNullableInt: Int = nullableInt!! // asserting and smart cast

转换值的另一种方法是通过空判断.在上面的代码中不有用,但在其他代码中有用(参见Checking for null in conditions):

val nullableInt: Int? = 1
if (nullableInt != null) {
   // allowed if nullableInt could not have changed since the null check
   val nonNullableInt: Int = nullableInt
}

这个问题也可以通过习惯性地处理可空性问题来回答:In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

Kotlin相关问答推荐

来自SnapshotFlow的单元测试StateFlow仅发出initialValue

判断字符串是否除了.&" ",","@""""

可以从背景图像中点击图标吗?

在 kotlin 中使具体化字段可选

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

使用事务时未调用 Kafka ConsumerInterceptor onCommit

如何将 `throw` 放置在辅助函数中但仍然具有空安全性?

Kotlin 中获取类简单名称的最佳实践

是否可以通过超时暂停协程?

如何使用 Kotlin KClass 属性 simpleName 生成空值

Android 在将 androidx 生物识别更新为 1.0.0-alpha04 后崩溃

如何使用 Kotlin Coroutines 使 setOnClickListener debounce 1 秒?

无法为 retrofit2.Call 调用无参数构造函数

Android 上的 Kotlin:将map到list

Kotlin:如何修改成对的值?

Java Integer.MAX_VALUE 与 Kotlin Int.MAX_VALUE

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

如何在使用Koin DI的活动之间共享同一个ViewModel实例?

Kotlin,什么时候按map授权?

Android Compose 生产准备好了吗?