在 Scala 中,如何在满足条件后立即停止从文件中读取行?
函数在 foreach 循环中读取行,并通过类似 CSV 的结构化文本文件中的键查找值。找到特定行后,继续阅读行寻找那里的东西是没有意义的。 Scala中没有break语句,如何停止?
Reading lines in a foreach loop, a function looks for a value by a key in a CSV-like structured text file. After a specific line is found, it is senseless to continue reading lines looking for something there. How to stop as there is no break statement in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Scala 的
Source
类是惰性的。您可以使用takeWhile
或dropWhile
读取字符或行,并且对输入的迭代无需超出所需的范围。Scala's
Source
class is lazy. You can read chars or lines usingtakeWhile
ordropWhile
and the iteration over the input need not proceed farther than required.扩展兰德尔的答案。例如,如果键位于第一列:
To expand on Randall's answer. For instance if the key is in the first column:
以前的答案假设您想要从文件中读取行,我假设您想要一种根据需要中断 for 循环的方法。
这是解决方案
你可以这样做:
Previous answers assumed that you want to read lines from a file, I assume that you want a way to break for-loop by demand.
Here is solution
You can do like this: