Reading User Input
Prerequisites: Type conversion
In a command-line program, readln() waits for the user to type a line
and press Enter, then returns it as a String.
Example
fun main() {
print("What's your name? ")
val name = readln()
println("Nice to meet you, $name!")
}
Expected output
What's your name? Ada
Nice to meet you, Ada!
(Ada is what the user typed.) Using print for the question keeps the
cursor on the same line.
readlnOrNull() returns null instead of throwing when there's no more
input — for example, when input is piped from a file that has ended.
Reading numbers
Input is always text, so convert it and handle invalid input:
fun main() {
print("How old are you? ")
val age = readln().trim().toIntOrNull()
if (age == null) {
println("Please enter a whole number.")
return
}
println("In ten years you'll be ${age + 10}.")
}
return inside main ends the program.
Note: the Kotlin Playground and Android apps don't read keyboard input this way. Run these examples from IntelliJ IDEA or a terminal.
Practice
Ask the user for their favorite color and print it back in capitals:
BLUE is a great color!.
Show solution
fun main() {
print("Favorite color? ")
val color = readln()
println("${color.uppercase()} is a great color!")
}