FWIW, here is what I will do (sticking to the standard library):
def firstLine(f: java.io.File): Option[String] = {
val src = io.Source.fromFile(f)
try {
src.getLines.find(_ => true)
} finally {
src.close()
}
}
Notes:
- The function returns
Option[String]instead List[String], since it always returns one or nothing. This is a more idiomatic Scala. src closed correctly even if you cannot open the file, but reading throws an exception- Using
.find(_ => true)to get the first element Iteratordoes not make me feel great, but there is no method nextOption, and this is better than converting to an intermediate Listone that you are not using. IOException .
scala-arm, API , .
import resource._
def firstLine(f: java.io.File): Option[String] = {
managed(io.Source.fromFile(f)) acquireAndGet { src =>
src.getLines.find(_ => true)
}
}