Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how to stop reading lines from a file as soon as a criterion is accomplished?

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?

like image 555
Ivan Avatar asked Aug 31 '10 04:08

Ivan


3 Answers

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.

like image 135
Randall Schulz Avatar answered Nov 18 '22 04:11

Randall Schulz


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()
like image 45
huynhjl Avatar answered Nov 18 '22 04:11

huynhjl


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
   }
 }
like image 23
Jeriho Avatar answered Nov 18 '22 05:11

Jeriho