The difference between !! and ? in Android Kotlin ❓
When it comes to null-safety in Kotlin, !! and ? operators can come in use. Now let’s see how they both are different from each other.
1️. !! operator
a. !! is the “not-null assertion” operator.
b. It is used to assert that a nullable value is not null.
c. It throws a NullPointerException if the value is null.
// Using !!
val str: String? = null
val length: Int = str!!.length // Throws NullPointerException
2. ? operator
a. On the other hand, ? is the “safe call” operator.
b. It is used to safely call methods or access properties on nullable values.
c. It returns null if the value is null.
// Using ?
val str: String? = null
val length: Int? = str?.length // length will be null
3. So, it is recommended to use ? operator for null-safety in Kotlin and only use !! operator when you are certain that the value is not null.