What is the difference between readLine() and readlnOrNull() in Kotlin?

1.5k Views Asked by At

As mentioned in Kotlin API document, readLine() returns the line read or null if end of file has already been reached but it is the same functionality as readlnOrNull(). So what is the difference here?

I know that readlnOrNull() and readln() have been introduced in Kotlin 1.6 for the purpose of null safety but I can't understand why readlnOrNull() introduced when readLine() exist before.

2

There are 2 best solutions below

1
Tenfour04 On BEST ANSWER

They added readlnOrNull as an alias of readLine for the sake of preserving the convention that each standard library function that throws a RuntimeException has an “orNull” version that returns null instead of throwing. It was added when readlnwas added. It’s so the matching function with this behavior can be easily found. If readLn had existed from the earliest version of Kotlin, then they might never have created a redundant readLine function that matches the behavior of readlnOrNull. They have not deprecated readLine because there’s nothing wrong with its behavior and it’s concise.

1
Sujoy Dhar On

readLine() and readlnOrNull() are both methods used in Kotlin for reading input from the user.

readLine() is used to read a line of text from the standard input and returns a string. If the user does not provide any input or an error occurs, this method throws an IOException.

scss

val input = readLine()

readlnOrNull() is similar to readLine(), but instead of throwing an exception, it returns null if the user does not provide any input or an error occurs.

scss

val input = readLine() ?: "No input provided"

In general, it is recommended to use readlnOrNull() as it provides a more flexible and safer way to handle input reading in Kotlin.