How do I use the safe call operator `?.` in Kotlin?

In Kotlin, the safe call operator ?. lets you access a property or call a function only if the value is not null.

If the value is null, the expression simply returns null instead of throwing a NullPointerException.

val name: String? = null

val length = name?.length

println(length) // null

Here, name is nullable because its type is String?. Since name is null, name?.length does not try to access .length; it returns null.

Basic syntax

nullableValue?.property
nullableValue?.function()

Example:

val user: User? = getUser()

val email = user?.email

If user is not null, email gets user.email.

If user is null, email becomes null.

Chaining safe calls

You can chain multiple safe calls together:

val city = user?.address?.city

This means:

  • if user is null, return null
  • otherwise check address
  • if address is null, return null
  • otherwise return city

Using ?. with a default value

Often, you combine ?. with the Elvis operator ?::

val length = name?.length ?: 0

This means:

  • if name is not null, use name.length
  • if name is null, use 0

Using ?.let

Use ?.let when you want to run code only when a value is not null:

val name: String? = "Kotlin"

name?.let {
    println("Name is $it")
    println("Length is ${it.length}")
}

The block runs only if name is not null.

Safe call on assignment

Safe calls can also be used on the left side of an assignment:

person?.address?.city = "Paris"

If person or address is null, the assignment is skipped.

Summary

val result = nullableValue?.someProperty

Use ?. when:

  • a value might be null
  • you want to avoid NullPointerException
  • returning null is acceptable when the receiver is null

Common pattern:

val result = nullableValue?.someProperty ?: defaultValue

How do I handle nullable types using the safe call operator ?. in Kotlin?

In Kotlin, the safe call operator (?.) is used to handle nullable types safely. It ensures that the property or method is accessed only if the value is non-null, avoiding the possibility of a NullPointerException.

Here’s how it works:

Syntax and Usage:

The ?. operator allows you to safely access a property or call a method on an object that could be null. If the object is null, the entire expression will evaluate to null, instead of throwing a NullPointerException.

Examples:

1. Accessing Properties:

val name: String? = null
val length = name?.length // Safe call, will return null because name is null
println(length) // Output: null

2. Calling Methods:

val nullableString: String? = "Hello"
println(nullableString?.toUpperCase()) // Output: "HELLO"

val nullString: String? = null
println(nullString?.toUpperCase()) // Output: null

3. Chaining Safe Calls:

You can chain multiple safe calls to handle deeply nested nullable types.

data class Address(val city: String?)
data class User(val address: Address?)

val user: User? = User(Address("New York"))
println(user?.address?.city) // Output: "New York"

val nullUser: User? = null
println(nullUser?.address?.city) // Output: null

4. Using with let:

You can combine the safe call operator with the let function to perform an action if the value is not null.

val name: String? = "Kotlin"
name?.let {
    println("The length of the name is ${it.length}")
}
// Output: The length of the name is 6

5. Elvis Operator (?:) for Default Values:

You can use the safe call operator with the Elvis operator (?:) to provide a default value when the expression evaluates to null.

val name: String? = null
val length = name?.length ?: 0 // If name is null, use default value 0
println(length) // Output: 0

Key Points:

  1. Avoids NullPointerException: The ?. operator prevents unsafe access to null objects.
  2. Returns null if the object is null: The chain will break and return null if any part of the chain is null.
  3. Useful for concise and readable code: It eliminates the need for explicit null checks.

By using the safe call operator, you can effectively and concisely handle nullable types in your Kotlin code.