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().
-
Edit the file
Check1.kt, in thetasks/task10_3_1subdirectory of your repository. This is basically the same asNull.kt, with the last line ofmain()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) } -
Try compiling the program. This time, it should compile successfully.
-
Test the program by running it with different inputs. Try pressing
Ctrl+Dwhen 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.
-
Edit the file
Check2.kt, in thetasks/task10_3_2subdirectory of your repository. This is basically the same asNull.kt, with the last line ofmain()uncommented. -
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 ofString. As a consequence of this, we have to do the null check inside the function, before attempting to reverse and uppercase the supplied string. -
Try compiling the program. It should compile successfully.
-
Test the program by running it with different inputs. Try pressing
Ctrl+Dwhen prompted. It should behave in exactly the same way asCheck1.kt.