๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin User Input

User input is text a person types while a program runs. The program reads the typed text one line at a time.

Reading a name

One line is read and held in name. The greeting uses that line.

fun main() {
    val name = readlnOrNull() ?: "friend"
    println("Hello, $name")
}

Reading a number

The line is read as text first. The safe call and toIntOrNull turn the text into the number 30.

fun main() {
    val age = readlnOrNull()?.toIntOrNull() ?: 0
    println(age)
}

Bad number text gives null

The text abc holds no number. toIntOrNull gives null instead of throwing an exception.

fun main() {
    val n = "abc".toIntOrNull()
    println(n)
}

Example

fun main() {
    val name = readlnOrNull() ?: "friend"
    val age = readlnOrNull()?.toIntOrNull() ?: 0
    println("Hello, $name, you are $age")
}

Key points

  • Use readlnOrNull to read one line of typed text
  • readlnOrNull gives a String? holding the line that was typed
  • The result is null when no line is left
  • Use toIntOrNull to turn text into a number or null
  • Use the elvis operator to supply a fallback for null

In this example, the first readlnOrNull reads the name line Ana. The second readlnOrNull reads the age line and toIntOrNull turns it into 30. The greeting prints both values in one line.

Note

Typed numbers arrive as text and need a conversion before maths.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does readlnOrNull give back when no line is left?