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

Time:06-11

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

[enter image description here][2]

I ve tried to run exactly the same code:

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

CodePudding user response:

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")
  • Related