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

An Example

  1. Go to the tasks/task10_1 subdirectory of your repository and open the file Null.kt in your editor. Study the code carefully.

    This program has a function printReversed(), which prints a reversed, uppercased version of the string passed to it.

    The main() function contains code to read a string from the user, print it, then invoke printReversed() on it. The last of these operations is currently commented out.

  2. Compile the code and run it. Enter some text when prompted.

  3. Try running it again, but this time press Ctrl+D when prompted for input. What happens?

  4. Uncomment the final line of main(), then try compiling the program again. What message you do see from the compiler?

Explanation

At first, before uncommenting that final line of main(), the program compiles and runs as you would expect. Entering some text results in that text being displayed. However, if you press Ctrl+D you should see the word “null” displayed.

This happens because readLine() is used to read input from the console. Unlike readln(), which throws an exception when the input stream is closed, readLine() returns the special value null instead.

When you uncomment the last line of main(), the program will no longer compile. The error message complains of an argument type mismatch:

actual type is 'String?', but 'String' was expected

But what does this mean, and how do we fix it?

Read on for answers to those questions…