Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Safe Call Operator

Basic Concept

Kotlin makes writing null-safe code a lot easier than Java does, first by controlling the locations where null checks ought to be done, and second by giving us more elegant tools for doing those checks.

The first of these tools is the safe call operator, ?.

You are already familiar with ., the regular call operator. We use this whenever we need to invoke a method or extension function on an object, or access one of its properties. The Kotlin compiler won’t allow use of . on an instance of a nullable type, unless a null check has been done—but it will allow ?. to be used with nullable values.

In effect, the safe call operator does the null check for us, as well as invoking the specified method or function if the null check establishes that the value is not null.

For example, if text is a variable of type String?, we can invoke the reversed() extension function on this variable like so:

val result = text?.reversed()

If text is null, nothing else occurs and null will be assigned to result. If text is not null, the function will be called and the value of result will be whatever the function returns—in this case, the contents of text, in reverse order.

Call Chains

If you have a call chain, you will need to repeat the use of safe call along the chain:

val result = text?.reversed()?.uppercase()

If the calls made in the chain are to functions that don’t themselves return nullable values, this can needlessly repeat the null checks—in which case, a more efficient approach is to use safe call once, in combination with the let() scope function:

val result = text?.let { it.reversed().uppercase() }

The argument passed to let() is, of course, a lambda expression… 😉

You can read this code as “if text is not null, let it be reversed and then uppercased, to produce a value for result”.

Task 10.4

  1. Copy Check2.kt from the task10_3_2 subdirectory of your repository to the task10_4 subdirectory. Rename the copy to SafeCall.kt.

  2. Edit SafeCall.kt and apply what you’ve learned about safe calling to simplify the definition of printReversed().

    You should be able to replace four lines with a single line of code.

  3. Compile and run the program. It should behave in exactly the same way as Check2.kt.