Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read all lines from stdin in kotlin?

Tags:

stdin

kotlin

I know it is possible to use a while loop to fetch a multi-line input from stdin using the readLine function.

Is there a function in kotlin to retrieve all lines at once from stdin without using a JVM api?

like image 236
Artenes Nogueira Avatar asked Nov 02 '25 12:11

Artenes Nogueira


1 Answers

val input = generateSequence(::readLine).joinToString("\n")
print(input)

The first line gets the multi-line input from stdin and put it into a variable.

The generateSequence is a function from kotlin standard library, kotlin.sequences package, that takes another function and calls it until it returns null. In the end it will return an instance of Sequence, that is a sequence of elements that can be iterated over.

The ::readLine part is a way to pass the readLine function, that it is used to read from stdin, to the generateSequence function. Just calling readLine() without :: will cause a compiler error since generateSequence expects for a lambda, not a string.

The joinToString method belongs to the Sequence class. It will iterate over its elements and join them using the given separator, which, in this case, is a new line (\n).

Finnaly at the second line we just print the result to the stdout.

like image 99
Artenes Nogueira Avatar answered Nov 04 '25 06:11

Artenes Nogueira