Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 21 / 68

Writing Null-Safe Code (the ?: Elvis operator)

In this lesson you will learn null-safe code in Kotlin with the Elvis operator, and how to avoid errors when a value has not been set. This is for anyone searching for "Kotlin Elvis operator how to use".

?: (the Elvis operator) uses the right-hand value only when the left is null. Taking null safety seriously at the language level is one of Kotlin's defining features.

The sample code writes address ?: "No address set" against a variable declared as val address: String? = null, showing a replacement string when there is no value. Adding ? after the type, as in String?, states explicitly that the type allows null.

A common stumbling block for beginners is that a variable declared without ? cannot hold null at all. Kotlin checks for the possibility of null at compile time, so nullable and non-nullable have to be distinguished strictly through the type.

In real-world development this mechanism makes it much easier to write code that does not throw NullPointerException - one of the big reasons Kotlin is so well regarded.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)