Kotlin

Kotlin

Made by DeepSource

Redundant use of ?. detected KT-W1063

Anti-pattern
Minor
Autofix

In Kotlin, ?. is called the "safe call operator" or "null-safe call operator". It is used to perform a safe access or safe method call on a nullable object. It allows you to execute a method or access a property on an object only if the receiver is not null. If the object is null, the expression will evaluate to null without throwing a NullPointerException.

Redundant use of ?. on a non-nullable receiver can make the code less readable and harder to maintain. It makes actually non-nullable values seem as if they were nullable, and forces code to be unnecessarily complex to handle such cases.

Only use ?. where it is required.

Bad Practice

fun getUser(id: String): User { // doesn't return a nullable type
    // ..
}
val userName = getUser()?.name // redundant safe-call
LOG.info { "$userName is logged in!" }

Recommended

Avoid usage of ?. where it's not required.

fun getUser(id: String): User { // doesn't return a nullable type
    // ..
}
val userName = getUser().name
LOG.info { "$userName is logged in!" }