The difference between !! and ? in Android Kotlin ❓

Mujeeb ur rahman khan
2 min readMay 1, 2023

--

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.

Thank you for reading this article. If you found this helpful and interesting, please clap and follow me for more such content.

If I got something wrong, mention it in the comments. I would love to improve.

Connect with me on GitHub and LinkedIn

--

--

Mujeeb ur rahman khan
Mujeeb ur rahman khan

Written by Mujeeb ur rahman khan

I am final year IT engineering student from India. I have deep interest in Android development. on my way to become better developer

No responses yet