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

OrNull()

Because Kotlin is good at dealing with nulls, there are a number of functions in the Kotlin standard library that return null.

For example, there is a readlnOrNull() function to go alongside readln(). It does the same things as readln(), except that it returns null if the input stream is closed rather than throwing an exception1.

When we considered input from the command line or console, we saw that the strings obtained from the user can be converted to other types with functions such as toInt(), toLong(), toFloat(), toDouble(). Each of these throws an exception if the string cannot be parsed successfully, but there is also an …OrNull() version of each of them that returns null when parsing fails.

When we considered collection types, we saw that there are extension functions like min(), max(), minBy() and maxBy(), for finding minimum and maximum values. Each of these throws an exception if invoked on an empty collection, but there is also an …OrNull() version of each of them that returns null for empty collections.

Important

Notice the pattern here: for each function that throws an exception if an operation can’t be carried out successfully, there is a counterpart, with OrNull appended to its name, that returns null if the operation can’t be carried out. This means we often have two distinct options for handling failed operations in our code.


  1. readlnOrNull() does effectively the same thing as the now-deprecated readLine().