Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading