Clean way of reading all input lines in Kotlin

不打扰是莪最后的温柔 提交于 2019-12-06 05:02:14

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.

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.

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