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?
views:
119answers:
3
+7
A:
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.
Randall Schulz
2010-08-31 04:31:44
+4
A:
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()
huynhjl
2010-08-31 06:46:32
Watch for exceptions on empty lines!
Elazar Leibovich
2010-08-31 20:24:09
Good example for me, but it raises one more question: how do I skip first line, which is a table header?
Ivan
2010-08-31 23:22:59
`val iter = src.getLines().drop(1).map(_.split(":"))`
huynhjl
2010-09-01 01:44:35