Consider the following code:

Example

fun main(args: Array<String>) {
    maybeWriteMessage()
}

fun maybeWriteMessage(message: String? = null) {
    writeMessage(message!!)
}

fun writeMessage(message: String) {
    println("Hello World")
}

Output

线程"main"kotlin中出现异常.KotlinNullPointerException在

This is because I'm passing message!! (null, damn it!) to a non-nullable parameter, however the parameter is never accessed.

Question

Why does Kotlin forcibly throw KotlinNullPointerException even when the null reference isn't accessed?

推荐答案

message: String? is indicating that message may or may not be null.

由于您的函数maybeWriteMessagemessage的默认值为null,并且您在调用maybeWriteMessage()时没有指定message,因此在调用writeMessage(message!!)时将使用默认值(null).

documentation中所述,!!运算符在值为null时引发异常.

One way to trigger writeMessage safely would be to use .let:

fun maybeWriteMessage(message: String? = null) {
    message?.let { 
      writeMessage(it)
    }
}

Kotlin相关问答推荐

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

相当于roomdb中的DateTime Bigint列的是什么

从 Kotlin 的父类获取函数注解

Kotlin 基于参数类型的返回类型推断

Rabin-Karp字符串匹配的实现(Rolling hash)

如何在 Spring Boot 3 中为内部类提供运行时提示

如果带注释的成员未被特定块包围,则发出 IDE 警告

如何创建扩展函数isNullOrEmpty?

Kotlin SAM/功能接口抛出 AbstractMethodError

匹配在单词边界上包含特殊字符的变量字符串的正则表达式

添加 Kapt 插件后 - 执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

如何为你的 Flutter 元素添加 Kotlin 支持?

对列表中数字的子集求和

Kotlin 中的数据类

kotlin:扩展方法和空接收器

将协同路由调用放在存储库或ViewModel中哪个更好?

应用程序在使用 Google Play 服务时遇到问题

在 suspendCoroutine 块中调用挂起函数的适当方法是什么?

Kotlin中的属性(properties)和参数(parameters)有什么区别?