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

Elvis operator doesn't work in Kotlin while the synthax seems correct

I am learning Kotlin from this [1] and at 35:45 he is running this code:

[enter image description here][2]

I ve tried to run exactly the same code:

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

fun main() {
val x = readLine()?:"1"
val y = readLine()?:"1"
val z = x.toInt() + y.toInt()
print(z)

}

But i get this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at MainKt.main(Main.kt:4)
at MainKt.main(Main.kt)

Can somebody help me please? I am really a noob in kotlin (and sofware programming too) and i didn’t found an answer on the web.

Thank you.
[1]: https://www.youtube.com/watch?v=5flXf8nuq60&t=302s
[2]: https://i.stack.imgur.com/nlHqi.jpg
[3]: https://i.stack.imgur.com/o7y2I.jpg

>Solution :

The Elvis operator evaluates to the right operand only when the left operand is null. The empty string "" is not the same as null.

readLine() returns null when it detects the "end of file". When reading from a file, this is obviously when reaching the end. When reading from stdin (the console’s standard input), this is usually when you press Ctrl+D.

If you just press Enter, you are effectively inputting an empty line (""), not the "end of file".

If you want to get this kind of default value when you press Enter on the command line, then you should react to the empty string instead of null. As @lukas.j mentioned, one way to do this is to use ifEmpty to provide a default:

val x = readln().ifEmpty("1")
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