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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With