Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 134 ยท Getting Started

Reading Input

Learn how Kotlin reads input - readln, readlnOrNull, readLine, parsing numbers with toInt and toIntOrNull, reading until end of input, splitting tokens and building small interactive programs.

So far our programs have only talked. Real programs also listen: they ask for a name, read numbers from a file, or process lines piped in from another command. In Kotlin, text comes in through standard input (stdin), and getting it right means handling two things: the line might not exist (end of input), and the text might not be what you expected (a user types twelve where you wanted 12).

On this site every example that reads input has a preset "Program input" box under the editor, one line per readln() call. On your own computer the same code waits for you to type in the terminal. This lesson shows the reading functions, safe number parsing, loops that read until the input ends, and a small interactive program. If you need a refresher on strings first, see Strings.

readln() and readlnOrNull()

readln() reads one line from standard input and returns it as a String, without the line break. It is the simplest tool:

Kotlin Asking for a name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

print (no ln) leaves the cursor on the same line, so the prompt and the answer appear together in a terminal. In the output box on this page you will see the prompt and the greeting; the input itself is in the box below the editor.

What if there is no next line, because the user pressed Ctrl+D or the input file ended? readln() throws ReadAfterEOFException (a subclass of RuntimeException). That is the right behavior when a missing line is a real error, but it is a crash if you only wanted "read while there is more":

Kotlin Reading past the end of input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line prints, and then the program stops with Exception in thread "main" kotlin.io.ReadAfterEOFException: EOF has already been reached. Use readlnOrNull() when the input may end: it returns null instead of throwing, and Kotlin's null-handling tools (see Null Safety) take over.

Kotlin readlnOrNull and the Elvis operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The ?: operator supplies a default when the left side is null. The older name readLine() also returns String? (it does what readlnOrNull() does) and is still common in existing code. Prefer readln() and readlnOrNull() in new code, because the names say what they do.

From text to numbers

Everything that arrives from stdin is a String. To compute with it you convert, and conversion can fail. Kotlin offers two families of functions:

  • toInt(), toDouble(), toLong() convert or throw NumberFormatException.
  • toIntOrNull(), toDoubleOrNull(), toLongOrNull() convert or return null.
Kotlin Parsing safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that toIntOrNull is strict: it does not accept spaces, decimals, or numbers outside the Int range. trim() first if the text might have stray spaces. Plain toBoolean() returns false for anything that is not "true", which hides typos; toBooleanStrictOrNull() accepts only "true" and "false".

The unsafe versions fail loudly. Run this to see the exact message:

Kotlin toInt on bad text (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You will see java.lang.NumberFormatException: For input string: "twelve". In a program where users type the numbers, prefer the OrNull versions and decide what to do on failure.

Asking until the answer is valid

Combine toIntOrNull, a loop and readlnOrNull to keep asking until you get a good value. Here the "user" types three attempts:

Kotlin Re-asking until valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The function returns Int?: a number, or null if the input ran out. That type forces the caller to handle the "no answer" case, which is exactly what a robust program needs. Note return inside ?: on the right side: return has type Nothing (it never produces a value), so the expression is still typed as String.

Several values on one line

Often a line carries several values, such as "3 4" or "10,20,30". Split it, then map each piece:

Kotlin Splitting a line into numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

val (a, b) = list is a destructuring declaration (see Pairs, Triples and Destructuring): it takes the first two elements of the list. mapNotNull applies a function and drops the null results, a compact way of saying "keep the valid ones". If the line has more than one space between numbers, split(" ") produces empty strings; in that case split on a regex such as Regex("\\s+") (see Regular Expressions).

Reading everything until the end

When you do not know how many lines will come, loop until readlnOrNull() gives null. generateSequence turns that pattern into a one-liner:

Kotlin Counting lines with a classic loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This loop reads every line and counts five, including the blank one. It also shows that stdin is a stream: after the loop the input is used up, and it can only be consumed once, so a program picks one reading style and sticks with it. Here is the idiomatic version, which keeps the lines and parses them:

Kotlin Reading all lines with generateSequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

generateSequence(::readlnOrNull) calls the function again and again and stops at the first null. The ::readlnOrNull is a function reference (see Higher-Order Functions). The sequence is lazy, so .toList() is what actually reads. If you want the whole input as one string, use System.in.bufferedReader().readText(), and for large inputs (competitive programming) wrap stdin once with System.in.bufferedReader() and call readLine() on that reader, which is faster than many separate readln() calls.

Scanner and BufferedReader

Kotlin runs on the JVM, so the Java readers are available too. You will meet two of them in older code, in tutorials written for Java, and in competitive-programming solutions.

java.util.Scanner splits input into whitespace-separated tokens and parses them for you. It is convenient when the input is "a few numbers, then a word":

Kotlin Reading tokens with Scanner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

System.in is a Kotlin keyword, so Java's System.in must be written with backticks: System.`in` . nextInt() throws InputMismatchException if the next token is not a number, and NoSuchElementException at the end of input, so guard with hasNextInt() or hasNext() as above.

BufferedReader reads whole lines and is much faster on large inputs, which matters when a program reads hundreds of thousands of lines. You parse the text yourself:

Kotlin Reading lines with BufferedReader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

readLine() returns String?; the null at the end of input is why we only call trim() on lines we know exist. In Kotlin the shorter System.in.bufferedReader() creates the same reader, and readln() / readlnOrNull() use one shared reader internally.

Pick one reader for a whole program. Each reader buffers ahead, so mixing Scanner with readln() (or two BufferedReader objects on the same stream) makes lines disappear: the first reader has already swallowed them.

Which should you use? Prefer readln() and readlnOrNull() in new Kotlin code. Use Scanner when you want token parsing without writing split, and BufferedReader (or System.in.bufferedReader()) when speed matters.

A tiny interactive program

Putting it together: a number-guessing game where the "player" supplies guesses on stdin. The secret number is fixed so the output is predictable:

Kotlin A guessing game driven by input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program handles all three situations that matter for input: a valid guess, a nonsense line (it asks again without counting an attempt), and the end of input. The final 40 is never read, because the loop ends at the correct guess. Real input is rarely clean, so a defensive structure like this saves hours of debugging.

Write functions that take an input source, such as a List<String> or a () -> String?, rather than calling readln() deep inside the logic. They are then easy to test with fixed data and reusable for files and network text. The projects later in this course (Expression Calculator) follow this pattern.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when readln() is called and there is no more input?

    readln() throws when input has ended. readlnOrNull() returns null instead.
  2. 2. What does "3.5".toIntOrNull() return?

    toIntOrNull accepts only valid whole numbers in the Int range. A decimal point makes the text invalid, so the result is null.
  3. 3. Which expression gives a default value when input has ended?

    readlnOrNull() has type String?, and ?: replaces a null result with the default. readln() never returns null, and !! would throw.
  4. 4. What does listOf("1", "x", "3").mapNotNull { it.toIntOrNull() } produce?

    mapNotNull keeps only the non-null results of the lambda, so the invalid "x" is dropped.
  5. 5. Why does a loop that reads all input once leave nothing for a second loop?

    Stdin is consumed as it is read. Read the lines into a list once, then process the list as often as you like.

Summary

  • readln() reads a line and throws at end of input; readlnOrNull() (and the older readLine()) returns null instead.
  • Input is always text. Convert with toInt() (throws NumberFormatException) or toIntOrNull() (returns null).
  • Use trim(), split(), mapNotNull and destructuring to handle several values per line.
  • generateSequence(::readlnOrNull).toList() reads all remaining lines.
  • Stdin can be read only once, so read it into a list if you need it more than once.
  • Design for bad and missing input from the start; return Int? and let the caller decide.

Next: Operators