干净的方式读取Kotlin中的所有输入行 [英] Clean way of reading all input lines in Kotlin

查看:154
本文介绍了干净的方式读取Kotlin中的所有输入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行编码挑战时的常见模式是读取多行输入.假设您事先不知道多少行,那么您要读取直到EOF(readLine返回null).

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).

作为序言,我也不想依赖java.utils.*,因为我使用KotlinNative进行编码,所以没有Scanner.

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

我想做类似的事情

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

但这显然不是有效的Kotlin.我能想到的最干净的是:

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)
}

这行得通,但似乎不是很惯用.有没有更好的方法可以将所有行读入数组,而无需使用while/break循环?

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?

推荐答案

generateSequence 具有很好的属性,如果内部生成器返回null并仅接受一次迭代,它将完成,因此以下代码可能有效:

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()

然后像 s1m0nw1的答案一样,您可以使用任何可用的Sequence<String>方法来根据您的解决方案进行优化

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

这篇关于干净的方式读取Kotlin中的所有输入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆