104

我正在定义一些用作回调的函数,但并非所有函数都使用它们的所有参数。

如何标记未使用的参数,以便编译器不会给我关于它们的警告?

4

4 回答 4

167

使用@Suppress注释您可以禁止对任何声明或表达式进行任何诊断。

示例:禁止参数警告:

fun foo(a: Int, @Suppress("UNUSED_PARAMETER") b: Int) = a

禁止声明中的所有 UNUSED_PARAMETER 警告

@Suppress("UNUSED_PARAMETER")
fun foo(a: Int,  b: Int) {
  fun bar(c: Int) {}
}

@Suppress("UNUSED_PARAMETER")
class Baz {
    fun foo(a: Int,  b: Int) {
        fun bar(c: Int) {}
    }
}

此外,IDEA 的意图(Alt+Enter)可以帮助您抑制任何诊断:

于 2015-03-14T08:19:41.790 回答
8

如果您的参数在 lambda 中,您可以使用下划线来省略它。这将删除未使用的参数警告。它还将防止IllegalArgumentException参数为空且被标记为非空的情况。

请参阅https://kotlinlang.org/docs/reference/lambdas.html#underscore-for-unused-variables-since-11

于 2017-10-20T15:39:31.177 回答
0

如果函数是类的一部分,则可以将包含类openabstract违规方法声明为open.

open class ClassForCallbacks {
  // no warnings here!
  open fun methodToBeOverriden(a: Int, b: Boolean) {}
}

或者

abstract class ClassForCallbacks {
  // no warnings here!
  open fun methodToBeOverriden(a: Int, b: Boolean) {}
}
于 2020-09-09T20:52:44.950 回答
-6

可以通过在 build.gradle 中添加 kotlin 编译选项标志来禁用这些警告。要配置单个任务,请使用其名称。例子:

compileKotlin {
    kotlinOptions.suppressWarnings = true
}

compileKotlin {
    kotlinOptions {
        suppressWarnings = true
    }
}

也可以在项目中配置所有的 Kotlin 编译任务:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        // ...
    }
}

如果有人在 Android 中使用 kotlin 并且想要抑制 kotlin 编译器警告,请在 app-module build.gradle 文件中添加以下内容

android{
    ....other configurations
    kotlinOptions {
        suppressWarnings = true
    }
}

无论您是否真的需要为您的项目取消所有 kotlin 警告,都取决于您。

于 2018-04-13T11:50:46.007 回答