Problem using readLine() in Playground

Hi

I’m new here and new to coding, so apologies if I do something wrong; just let me know!

I managed to install “IntelliJ IDEA (Community Edition)” on my pc and start writing basic Kotlin programs. I also test some of the code @ play.kotlinlang.org. But now I have a problem. The following code works as expected when run in IntelliJ:

fun main() {
println(“What is your name?”)
val name = readLine()
println(“Hello $name!”)
}

But when copy and pasted into Playground I get the following result:

What is your name?
Hello null!

with no chance to enter any text.

Is this a problem with:
a) Playground
b) how I am using Playground
c) my code
d) something else?

I have tried searching the main website and the forums but can’t find anything that helps. Any help would be appreciated.

Thanks

The playground runs the code instantly, and so AFAIK you have to put your user input separated by commas in the program arguments in the settings menu

1 Like

Thank you for your reply kyay10. The first part helps explain what is going on. As for the second part, I tried your suggestion, but I still get the same result unfortunately. My search for a solution continues…

1 Like

If you use arguments you must take them into your code with the main method fun main(args: Array<String>).

I don’t think you can get interactive input on Kotlin Playground. I could be wrong though. Personally I would just write my own readline function to only use on Kotlin Playground.

val input = mutableListOf("first", "second")
fun readLine(): String? {
    val line = input.firstOrNull()
    input.removeAt(0)
    return line
}

fun main() {
    println(readLine())
    println(readLine())
}

In IntelliJ, you can use the Kotlin REPL under the “tools” menu.

You can also write Kotlin scripts and run them directly using “new” → “scratch file” → “kotlin”. You’ll get a file with a run button that works in interactive mode and optionally as a REPL if you want. It also supports using the classpath of your project, meaning you can write and test these Kotlin scratch files using the classes and methods defined in your normal project.

3 Likes

Wow!

Thank you @arocnies for giving so much information. At this point in my ‘learning to code’ journey I won’t pretend I fully understand your reply. When I posted I thought there would be an easy answer. However, you have given me plenty to investigate and try out on the next steps of my journey. It may take some time!

Thanks again.

2 Likes