2

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

attachment_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)

attachment_3

Can somebody help me please? I am really a noob in Kotlin (and software programming too) and I haven't found an answer on the web.

Thank you.

bighugedev
  • 379
  • 1
  • 3
  • 11
  • 1
    `readLine` only returns null if it reads from a file and end of file has been reached. You are getting the empty string when you just press enter in the console. – marstran Jun 11 '22 at 13:33
  • 1
    Use _readlnOrNull()_ if you want to get _null_ instead of an empty string. – lukas.j Jun 11 '22 at 13:34
  • Please do not post pictures of code or errors, copy-paste the text instead: https://meta.stackoverflow.com/q/285551/1540818 – Joffrey Jun 11 '22 at 13:34
  • @marstran First thank for your answer. Can you be more precise please. Yes i am getting getting the empty string when i press enter in the console and so where is the problem? It like that that i made the input as null no? – constellation_du_fion Jun 11 '22 at 13:35
  • @lukas.j I am following a course on internet (see video link) so i prefer to learn what i made wrong. – constellation_du_fion Jun 11 '22 at 13:37
  • 2
    @lukas.j `readlnOrNull` behaves exactly the same way as `readLine` on the JVM. It too will return the empty string. – marstran Jun 11 '22 at 13:38
  • 1
    @constellation_du_fion: What you are looking for is: _readln().ifEmpty { "1" }_ – lukas.j Jun 11 '22 at 13:38
  • 1
    @marstran: was not aware that. Thank you for correcting me on this. – lukas.j Jun 11 '22 at 13:39

1 Answers1

4

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" }
Joffrey
  • 32,348
  • 6
  • 68
  • 100