如何让 Kotlin 编译器将警告视为错误?

How do I make the Kotlin compiler treat warnings as errors?

我有一个 Kotlin 项目,我希望在其中将 Kotlin 警告视为错误。我该怎么做?

Kotlin command-line 帮助或 Kotlin 编译器可用的参数目前似乎不可用:

K2JVMCompilerArguments.java

CommonCompilerArguments.java

但是 Gradle 中的一些人会这样做来扫描编译器的日志记录,以了解何时生成了警告。

在可用于 Kotlin(Intellij IDEA 和 Eclipse)的 IDE 插件中,没有这样的选项。

您应该在 YouTrack 中提交功能请求(或检查是否已经存在),其中包含 Kotlin 项目的所有问题跟踪。如果您这样做,请 post 在此处提交问题以便对其进行跟踪。

自 Kotlin 1.2 起,支持命令行参数 -Werror。在 Gradle 中,它被命名为 allWarningsAsErrors:

compileKotlin {
    kotlinOptions.allWarningsAsErrors = true
}

如果您正在使用 android,请改用它。在 Android 中,我们没有 compileKotlin,而是 compileDebugKotlin、compileReleaseKotlin 等。所以我们必须遍历它们并将此配置添加到所有这些。

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        kotlinOptions.allWarningsAsErrors = true
    }
}

使用 Kotlin DSL:

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        kotlinOptions.allWarningsAsErrors = true
    }
}

使用最新版本的 Android Gradle 插件,可以简单地执行以下操作:

android {
    kotlinOptions {
        kotlinOptions.allWarningsAsErrors = true
    }

    ...
}