扩展Randall的答案.例如,如果密钥位于第一列:
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()
Run Code Online (Sandbox Code Playgroud)
以前的答案假设您想要从文件中读取行,我假设您想要一种根据需要中断 for 循环的方法。这是解决方案 您可以这样做:
breakable {
for (...) {
if (...) break
}
}
Run Code Online (Sandbox Code Playgroud)