Redundant use of `!!` detectedKT-W1062
The not-null assertion operator !!
tells the compiler that a nullable variable is guaranteed to be non-null, even though
the type system says otherwise. It allows you to forcefully unwrap a nullable type.
This can be a useful tool when performing operations where the compiler isn't able to determine null safety correctly.
However, this operator is not always required. For example, if a value is known to not be null (its type is not suffixed with a ?
), there is no need to use !!
explicitly.
Similarly, if a value has been smartcast to a non-null type via a condition, the compiler will already know that the value is safe to use, and !!
isn't required in such cases either.
Redundant use of !!
can make the code less readable and harder to maintain. It can obscure the presence of null values, leading to subtle bugs in the future.
Only use !!
when it is absolutely required.
Bad Practice
fun example() {
val a = 1
val b = a!! // no need, a is not nullable
println(b)
}
Recommended
Avoid usage of !!
where it's not required.
fun example() {
val a = 1
val b = a
println(b)
}