Avoid not-null assertions with `!!`KT-E1010
Using the non-null assertion operator (!!
) on a nullable value may throw a NullPointerException
at runtime. When it is used, the compiler is forced to assume that the target value is non-null, and will thus allow operations that may throw NPEs.
Sometimes, it is possible for a value to definitely be non-null, even if the compiler does not think so. This can happen when you are working with mutable variables in single threaded code, where the compiler is unable to assume that a variable's value has not changed between any null checks and any subsequent accesses.
If you are absolutely sure that a variable will never be null at some point, consider adding a skipcq
comment on the specified line, like below:
`something!! // skipcq: KT-E1010
Bad Practice
fun myFunction(str: String?) {
println(str!!.length) // Bad!!
}
Recommended
Use the safe call operator ?.
, the Elvis operator ?:
, or conditional expressions to handle nullable values in a more
controlled manner without risking runtime exceptions.
fun myFunction(str: String?) {
println(str?.length)
}