kotlinuser-input

Why does my Kotlin program fail to compile?


I'm currently learning Kotlin and using https://play.kotlinlang.org/ to compile my code.
I tried to create a very simple program, collecting user input and giving output.
Howevery, it doesn't run.

fun main() {
   println("Give me a number of minutes!") 
   var input:String = readLine()!!
   var inputInMinutes = input.toInt()
   var resultInSeconds:Int = 0
   resultInSeconds = (inputInMinutes*60)
   println("That is " + resultInSeconds + " seconds!") 
}

I was expecting the program to compile and run, but it displays the following error message:

Give me a number of minutes!
Exception in thread "main" java.lang.NullPointerException
 at FileKt.main (File.kt:7) 
 at FileKt.main (File.kt:-1) 
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2) 

Is there a mistake in my code or does the online IDE not allow for user input?


Solution

  • Why does my Kotlin program fail to compile?

    Actually it does compile without errors.
    An exception like you observed is thrown at runtime, not compile time.

    Regarding your specific exception:
    According to this post in the site's forum, the Kotlin Playground does not suppport interactive input (like you attempted with readLine()).
    Therefore readLine() returns null, and as @KlitosKyriacou rightly pointed out to me readLine()!! which performs a null-assertion then throws the exception you see (originally I mistakenly assumed the exception was thrown by input.toInt()).

    A possible solution (as suggested in the post mentioned above) is to write your own function that emulates readLine():

    val input = mutableListOf("123") // here you should put your input
    fun myReadLine(): String? {
        val line = input.firstOrNull()
        input.removeAt(0)
        return line
    }
    
    fun main() {
       println("Give me a number of minutes!") 
       var input:String = myReadLine()!!
       var inputInMinutes = input.toInt()
       var resultInSeconds:Int = 0
       resultInSeconds = (inputInMinutes*60)
       println("That is " + resultInSeconds + " seconds!") 
    }
    

    Output:

    Give me a number of minutes!
    That is 7380 seconds!
    

    Live demo