In Scala, how to stop reading lines from a file as soon as the criteria is met?

Reading lines in a foreach loop, the function looks up the value using the key in a structured text file like CSV. After a certain line is found, it makes no sense to continue reading lines that are looking for something there. How to stop since in Scala? No break expression?

+6
loops scala file-io break csv
source share
3 answers

The previous answers suggested that you want to read lines from a file, I assume that you want for-loop to be broken on demand. Here is the solution you can do as follows:

breakable { for (...) { if (...) break } } 
+2
source share

Scala Source class is lazy. You can read characters or strings using takeWhile or dropWhile , and input iteration should not go further than required.

+9
source share

To extend the answer to Randall. For example, 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() 
+6
source share

All Articles