KT.CAN_BE_NON_NULLABLE

Variable can be non-nullable

This rule inspects variables marked as nullable and reports which could be declared as non-nullable instead.

Noncompliant Code

Copy
class A {
    var a: Int? = 5
    fun foo() {
        a = 6
    }
}
class A {
    val a: Int?
        get() = 5
}
fun foo(a: Int?) {
    val b = a!! + 2
}
fun foo(a: Int?) {
    if (a != null) {
        println(a)
    }
}
fun foo(a: Int?) {
    if (a == null) return
    println(a)
}

Compliant Code

Copy
class A {
    var a: Int = 5
    fun foo() {
        a = 6
    }
}
class A {
    val a: Int
        get() = 5
}
fun foo(a: Int) {
    val b = a + 2
}
fun foo(a: Int) {
    println(a)
}

The content on this page is adapted from the Detekt Docs. Copyright ©2022 The Detekt Team. All rights reserved. https://detekt.dev/comments.html