Beginner 5 min readKotlin 2.0

Kotlin readln() — Reading User Input from the Console

Use readln() to read a line of text from the user. This tutorial covers reading strings, numbers, and handling input safely.

What You Will Learn

  • Use readln() to read a line
  • Convert input to Int or Double
  • Handle invalid input safely
  • Difference between readln and readLine

Reading a String

readln() reads one line of text from standard input and returns it as a String. It is the modern replacement for readLine().

Reading a String

kotlin
fun main() {
    println("Enter your name:")
    val name = readln()
    println("Hello, $name!")
}
Output
Enter your name: [user types: Juned] Hello, Juned!

readln() blocks until the user presses Enter and returns the typed text as a String. The output depends on what the user types.

Beginner Tip: The Kotlin Playground does not support interactive input. Test readln() programs in IntelliJ IDEA or from the command line.
readln() was added in Kotlin 1.6. For older projects, use readLine()!! (note the !! to assert non-null).

Reading Numbers

readln() always returns a String. To get a number, convert it with .toInt(), .toDouble(), etc.

Reading an Integer

kotlin
fun main() {
    print("Enter a number: ")
    val number = readln().toInt()
    println("Double: ${number * 2}")
}
Output
Enter a number: [user types: 7] Double: 14

.toInt() converts the String to Int. If the user types a non-number, this throws a NumberFormatException.

Common Mistake: Always validate user input before converting. If the user types "hello" and you call .toInt(), the program crashes.

Safe Input Conversion

Use .toIntOrNull() for safe conversion. It returns null if the input is not a valid number.

Safe Conversion with toIntOrNull

kotlin
fun main() {
    print("Enter a number: ")
    val input = readln()
    val number = input.toIntOrNull()
    if (number != null) {
        println("Square: ${number * number}")
    } else {
        println("That is not a valid number")
    }
}
Output
Enter a number: [user types: 5] Square: 25

toIntOrNull() returns null instead of throwing an exception when the input cannot be converted. This is the safe way to handle user input.

Best Practice: Always prefer toIntOrNull() over toInt() for user input. Users make mistakes.

Practice Exercise

Exercisemultiple choice

What does readln().toIntOrNull() return when the user types "abc"?

Quick Quiz

Quick Quiz

What is the return type of readln()?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-01Kotlin 2.0

Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review