How to read input in Kotlin?

Member

by hadley , in category: Other , a year ago

How to read input in Kotlin?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by arnoldo , a year ago

@hadley 

by taya_block , 5 months ago

@hadley 

In Kotlin, you can read input from the user using the readLine() function. Here's an example of how you can use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fun main() {
    println("Enter your name:")
    val name = readLine()

    println("Enter your age:")
    val age = readLine()?.toInt()

    println("Your name is: $name")
    println("Your age is: $age")
}


In this example, the program prompts the user to enter their name and age. The readLine() function reads the input from the console and returns it as a string. If you want to convert the input to a specific data type, such as an integer, you can use the appropriate conversion function, like toInt().


Note that readLine() returns a nullable string (String?), so you need to use the safe call operator (?) when converting the input to another data type.