?, !! and ?:
- Kotlin course
- Beginner
- Lesson 78/116
- 5 min
Learn safe call, non-null assertion and Elvis operators.
Safe call, non-null assertion and Elvis
Three operators work with null. ?. is the safe call: if the receiver is null the result is null. !! is the non-null assertion: if the receiver is null it throws NullPointerException. ?: is the Elvis operator: if the left is null it returns the right side.
val name: String? = null
name?.length // null
name!!.length // Exception!
name ?: "Guest" // GuestThese three operators manage null-risk in one line. Which one you choose depends on what you want to do when the value is null.
Usage examples of the three operators
name?.length safely fetches the length; if name is null the result is null, no exception. name!!.length is for those who say "I am sure it is not null"; if you are wrong, the app crashes.
val len = name?.length // Int?
val forced = name!!.length // Int (or Exception)
val display = name ?: "Guest" // StringThe Elvis operator is especially handy when you want to give a default: name ?: "Guest" returns "Guest" when name is null, otherwise name itself.
Practice Handle name with safe call and Elvis
Define a val name: String? = null. Print the safe length with println(name?.length) and the default name with println(name ?: "Guest") on separate lines.
Starter code
fun main() {
val name: String? = null
// Print the safe length and the default name on separate lines
}Sample solution
fun main() {
val name: String? = null
println(name?.length)
println(name ?: "Guest")
}Expected output
null Guest
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match operator to behavior
| Term | Meaning |
|---|---|
?. |
Safe call (null if null) |
!! |
Non-null assertion (exception if null) |
?: |
Elvis (default if null) |
String? |
Nullable type |
2 val len = name?.length — what is len if name is null?
- 0
- null Correct answer
- -1
- Throws an exception
Explanation: The safe call (?.) returns null on a null receiver; no exception.
3 Fill in the blank: Elvis default
val display = name ____ "Guest"
val display = name ?: "Guest"
Explanation: name ?: "Guest" gives a default when null.