I am not able to use ?: operator in Kotlin. It still doesn't make sense to me how and when should we use it. Can anyone please let me know about it?
Think of a scenario, where you need the length of a username. Now, the username itself could be null for different reasons and you’ll get the famous NullPointerException if you try to get the length from this username - which is null. This is not a good user experience.
But if somehow, when the username is null, we could return some integer values, then our app would not crash!
In this type of cases, we can make use of Elvis operator (?:).
Here’s a code snippet:
var username: String? = null
fun main() {
val firstResult: Int = username!!.length //Gives NPE and the app crashes
println(firstResult)
val secondResult: Int = username?.length ?: -1 //By using ?: operator, the app survives with -1 value
println(secondResult)
}
The left side of ?: operator will be considered if it is non-null. But if it is null, then the right side of ?: operator will be executed.
This is how Elvis operator (?:) works.