Search code examples
kotlinkotlin-native

Clean way of reading all input lines in Kotlin


A common pattern when doing coding challenges is to read many lines of input. Assuming you don't know in advance how many lines, you want to read until EOF (readLine returns null).

Also as a preface, I don't want to rely on java.utils.* since I'm coding in KotlinNative, so no Scanner.

I would like to maybe do something like

val lines = arrayListOf<String>()
for (var line = readLine(); line != null; line = readLine()) {
    lines.add(line)
}

But that clearly isn't valid Kotlin. The cleanest I can come up with is:

while (true) {
    val line = readLine()
    if (line == null) break
    lines.add(line)
}

This works, but it just doesn't seem very idiomatic. Is there a better way to read all lines into an array, without using a while/break loop?


Solution

  • generateSequence has the nice property that it will complete if the internal generator returns null and accepts only a single iteration, so the following code could be valid:

    val input = generateSequence(::readLine)
    val lines = input.toList()
    

    Then like s1m0nw1's answer you can use any of the available Sequence<String> methods to refine this as desired for your solution.