在 Scala 中,如何在满足条件后立即停止从文件中读取行?

发布于 2024-09-16 11:19:29 字数 99 浏览 4 评论 0原文

函数在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海拔太高太耀眼 2024-09-23 11:19:29

Scala 的 Source 类是惰性的。您可以使用 takeWhiledropWhile 读取字符或行,并且对输入的迭代无需超出所需的范围。

Scala's Source class is lazy. You can read chars or lines using takeWhile or dropWhile and the iteration over the input need not proceed farther than required.

记忆で 2024-09-23 11:19:29

扩展兰德尔的答案。例如,如果键位于第一列:

val src = Source.fromFile("/etc/passwd")
val iter = src.getLines().map(_.split(":"))
// print the uid for Guest
iter.find(_(0) == "Guest") foreach (a => println(a(2)))
// the rest of iter is not processed
src.close()

To expand on Randall's answer. For instance if the key is in the first column:

val src = Source.fromFile("/etc/passwd")
val iter = src.getLines().map(_.split(":"))
// print the uid for Guest
iter.find(_(0) == "Guest") foreach (a => println(a(2)))
// the rest of iter is not processed
src.close()
挽清梦 2024-09-23 11:19:29

以前的答案假设您想要从文件中读取行,我假设您想要一种根据需要中断 for 循环的方法。
这是解决方案
你可以这样做:

breakable {
   for (...) {
     if (...) break
   }
 }

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:

breakable {
   for (...) {
     if (...) break
   }
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文