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

Null Checks

Fixing the compiler error in Null.kt requires that we add a null check. We can do this using an if or when expression (although there are better ways, which we will consider shortly).

First Approach

The most obvious fix is to do a null check before calling printReversed().

  1. Edit the file Check1.kt, in the tasks/task10_3_1 subdirectory of your repository. This is basically the same as Null.kt, with the last line of main() uncommented.

    We’ve already seen that this final line, invoking printReversed(), causes a compiler error. Replace it now with this code:

    when (input) {
        null -> println("Result: null")
        else -> printReversed(input)
    }
    
  2. Try compiling the program. This time, it should compile successfully.

  3. Test the program by running it with different inputs. Try pressing Ctrl+D when prompted.

Think about what is happening here. The when expression creates two execution paths for the program: in the first, input is known to have the value null; in the second, we have established that input is NOT equal to null, so it must therefore be a valid string.

In this second branch, the compiler is happy to treat the String? object as if it had been a String object all along, and we are free to use it as an argument to printReversed(). This is sometimes referred to as smart casting.

Note that there is no conversion of one object into another taking place here, and therefore no runtime cost, aside from the cost of doing the null check in the first place. You can think of nullability as a kind of label attached to an object, indicating uncertainty. Examining the object via a null check removes the uncertainty and erases that label.

Second Approach

An alternative approach is to leave the main program as it is and instead change the definition of printReversed() so that it can handle nullable strings.

  1. Edit the file Check2.kt, in the tasks/task10_3_2 subdirectory of your repository. This is basically the same as Null.kt, with the last line of main() uncommented.

  2. Modify the printReversed() function so that it looks like this:

    fun printReversed(text: String?) {
        when (text) {
            null -> println("Result: null")
            else -> println("Result: ${text.reversed().uppercase()}")
        }
    }
    

    Notice what has changed here. The function parameter now has the type String? instead of String. As a consequence of this, we have to do the null check inside the function, before attempting to reverse and uppercase the supplied string.

  3. Try compiling the program. It should compile successfully.

  4. Test the program by running it with different inputs. Try pressing Ctrl+D when prompted. It should behave in exactly the same way as Check1.kt.