An Example
-
Go to the
tasks/task10_1subdirectory of your repository and open the fileNull.ktin 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 invokeprintReversed()on it. The last of these operations is currently commented out. -
Compile the code and run it. Enter some text when prompted.
-
Try running it again, but this time press
Ctrl+Dwhen prompted for input. What happens? -
Uncomment the final line of
main(), then try compiling the program again. What message you do see from the compiler?
Explanation
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…