Avoid using not-null assertions (`!!`) when safer alternatives exist. Instead: 1. Use safe calls (`?.`) when accessing properties or methods on nullable references
Avoid using not-null assertions (!!
) when safer alternatives exist. Instead:
?.
) when accessing properties or methods on nullable references?:
) to provide default valuesFor example, instead of:
val result = nullableValue!!.doSomething()
Prefer:
// Safe call with elvis operator
val result = nullableValue?.doSomething() ?: defaultValue
// Or early return with null check
if (nullableValue == null) {
return defaultValue // or handle the null case appropriately
}
val result = nullableValue.doSomething()
This pattern reduces the risk of NullPointerExceptions and makes code more robust. When reviewing code, look for unnecessary not-null assertions that could be replaced with safer constructs, as shown in the UnnecessaryNotNullAssertionFix
class. Additionally, follow the pattern seen in the expression typing code where early returns are used when a descriptor is null.
Enter the URL of a public GitHub repository