在Kotlin中标记未使用的参数

时间:2015-03-14 07:39:17

标签: suppress-warnings kotlin unused-variables

我定义了一些用作回调的函数,并不是所有函数都使用它们的所有参数。

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

4 个答案:

答案 0 :(得分:79)

使用@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)可以帮助您抑制任何诊断:

答案 1 :(得分:4)

如果您的参数位于lambda中,则可以使用下划线来省略它。这将删除未使用的参数警告。如果参数为null并且标记为非null,它也会阻止IllegalArgumentException

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

答案 2 :(得分: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) {}
}

答案 3 :(得分:-1)

可以通过在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警告,取决于您。