Menu
Coddy logo textTech

Safe Call Operator

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 14 of 93.

When you have a nullable variable, you can't directly call methods or access properties on it: the compiler won't allow it because the value might be null. The safe call operator ?. solves this problem elegantly.

Instead of using a regular dot ., you use ?. to safely access members of a nullable type:

fun main() {
    val name: String? = "Alice"
    val length = name?.length  // Returns 5
    println(length)
    
    val nullName: String? = null
    val nullLength = nullName?.length  // Returns null (no crash!)
    println(nullLength)
}

The safe call operator checks if the value is null before accessing the property or method. If the value is null, the entire expression returns null instead of crashing. If the value exists, it works just like a normal call.

You can also chain multiple safe calls together:

fun main() {
    val text: String? = "Hello"
    val result = text?.uppercase()?.length
    println(result)  // Prints: 5
}

If any part of the chain is null, the entire expression safely returns null without throwing an error.

challenge icon

Challenge

Easy

You are provided with the following nullable variable:

val message: String? = "Kotlin"

Use the safe call operator to:

  1. Get the length of message and print it
  2. Convert message to uppercase and print the result

Then, create another nullable variable:

val empty: String? = null

Use the safe call operator to get the length of empty and print it.

Each result should be printed on a separate line. Remember: the safe call operator returns null when the value is null.

Try it yourself

fun main() {
    val message: String? = "Kotlin"
    
    // TODO: Use the safe call operator to get the length of message and print it
    
    // TODO: Use the safe call operator to convert message to uppercase and print it
    
    val empty: String? = null
    
    // TODO: Use the safe call operator to get the length of empty and print it
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground