Introduction
Once a variable is declared nullable in Kotlin, you cannot call methods or access properties on it directly, since doing so could throw an exception if the value is actually null. Instead of writing verbose if-null checks everywhere, Kotlin provides two concise operators built specifically for this: the safe call operator ?. and the Elvis operator ?:. Together they let you navigate nullable values, chain calls safely, and supply fallback defaults in a single, readable expression.
Cricket analogy: You can't assume a nullable 'nightwatchman' field is set before checking, just as Kotlin forbids calling methods on a nullable variable without first confirming it isn't null, avoiding a crash mid-innings.
Syntax
// Safe call: returns null instead of throwing if str is null
val len: Int? = str?.length
// Elvis operator: supplies a default when the left side is null
val len2: Int = str?.length ?: 0
// Chaining safe calls across multiple nullable links
val city: String? = person?.address?.cityExplanation
The safe call operator ?. evaluates the expression on its left; if that expression is null, the whole call short-circuits and evaluates to null instead of throwing an exception, and if it is not null, the call proceeds normally. Safe calls can be chained, so a?.b?.c returns null immediately if a is null or if a.b is null, without ever crashing. The Elvis operator ?: is typically paired with a safe call: it evaluates the expression on its left, and if that result is null, it evaluates and returns the expression on its right instead. Elvis is also commonly used with return or throw on the right-hand side to implement early-exit patterns, such as returning from a function immediately when a required value is missing.
Cricket analogy: team?.captain?.averageScore short-circuits to null if the team or captain is missing, without crashing, then team?.captain?.averageScore ?: 0 supplies a default of 0, just like using ?: return early if a required player isn't named.
Example
data class Address(val city: String?)
data class Person(val name: String, val address: Address?)
fun greet(person: Person?) {
val city = person?.address?.city ?: "Unknown City"
val name = person?.name ?: return // early exit if person is null
println("$name lives in $city")
}
fun main() {
greet(Person("Ava", Address("Chennai")))
greet(Person("Sam", null))
greet(null)
}Output
Ava lives in Chennai
Sam lives in Unknown City
(nothing printed for the third call; greet returns early)Key Takeaways
- ?. accesses a member only if the receiver is non-null, otherwise it evaluates to null.
- Safe calls can be chained across multiple nullable links, e.g. a?.b?.c.
- ?: supplies a default value when the expression on its left is null.
- ?: is often combined with return or throw for early-exit null handling.
- Together, ?. and ?: replace verbose if-null boilerplate with a single readable expression.
Practice what you learned
1. What does str?.length evaluate to when str is null?
2. What does the expression str?.length ?: 0 return when str is null?
3. Which pattern is idiomatic for exiting a function early when a required parameter is null?
4. Given val city = person?.address?.city, what happens if person is non-null but person.address is null?
Was this page helpful?
You May Also Like
Null Safety in Kotlin
Kotlin's type system distinguishes nullable from non-nullable types at compile time, eliminating most NullPointerExceptions before code ever runs.
Smart Casts in Kotlin
After a null-check or type-check, Kotlin's compiler automatically treats a variable as the narrowed type within that scope, no explicit cast needed.
Functions in Kotlin
Learn how to declare, call, and simplify functions in Kotlin, including single-expression syntax and the Unit type.
Extension Functions in Kotlin
Learn how Kotlin extension functions let you add new behavior to existing classes without modifying or inheriting them.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics