Why is string template from readLine not working in Kotlin?

172 Views Asked by At

My code:

fun main() { 
    println("What's your name?")
    val name= readLine()
    println("Hello $name")
} 

Output:
What's your name?
Abhas
Hello

My question is: Why $name is not getting printed? After taking input ' Abhas ' it doesn't show anything and then after I pressed Enter and it prints ' Hello ' only.

1

There are 1 best solutions below

0
cactustictacs On

I'm not sure why it's not working for you - it is reading some input or it wouldn't get to the println statement, and it is printing the value of name (which has a value, otherwise it would say null).

At a guess, it's something to do with the way you're providing input, where the first line it reads is empty, so you get an empty string (""). You said your output is like this:

What's your name?
Abhas
Hello

Are you hitting enter/return to get to the next line before you type Abhas? That does nothing in the REPL I'm using, but it might count as an (empty) input line in your console