Clean way of reading all input lines in Kotlin

 ̄綄美尐妖づ 提交于 2019-12-08 00:21:06

问题


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?


回答1:


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.




回答2:


I guess you're talking about reading from System.in here? You could make that work with sequences:

val lines = generateSequence(readLine()) {
    readLine()
}

lines.take(5).forEach { println("read: $it") }

We begin our sequence with a first readLine (the sequence's seed) and then read the next line until null is encountered. The sequence is possibly infinite, therefore we just take the first five inputs in the example. Read about detials on Sequence here.



来源:https://stackoverflow.com/questions/53575064/clean-way-of-reading-all-input-lines-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!