Mark unused parameters in Kotlin

隐身守侯 提交于 2019-11-27 14:29:03

问题


I am defining some functions to be used as callbacks and not all of them use all their parameters.

How can I mark unused parameters so that the compiler won't give me warnings about them?


回答1:


With the @Suppress annotation You can suppress any diagnostics on any declaration or expression.

Examples: Suppress warning on parameter:

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

Suppress all UNUSED_PARAMETER warnings inside declaration

@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) {}
    }
}

Additionally IDEA's intentions(Alt+Enter) can help you to suppress any diagnostics:




回答2:


If your parameter is in a lambda, you can use an underscore to omit it. This removes the unused parameter warnings. It will also prevent IllegalArgumentException in the case that the parameter was null and was marked non-null.

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




回答3:


One can disable these warnings by adding a kotlin compile option flag in build.gradle. To configure a single task, use its name. Examples:

compileKotlin {
    kotlinOptions.suppressWarnings = true
}

compileKotlin {
    kotlinOptions {
        suppressWarnings = true
    }
}

It is also possible to configure all Kotlin compilation tasks in the project:

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

If one is using kotlin in Android and want to suppress kotlin compiler warnings, add below in app-module build.gradle file

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

Whether you really need to suppress all kotlin warning for your project or not, its up to you.



来源:https://stackoverflow.com/questions/29046636/mark-unused-parameters-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!