Read a specific line from a file: Difference between revisions

Line 680:
<lang scala>val lines = io.Source.fromFile("input.txt").getLines
val seventhLine = lines drop(6) next</lang>
 
Solving the task to the letter, imperative version:
 
<lang scala>var lines: Iterator[String] = _
try {
lines = io.Source.fromFile("input.txt").getLines drop(6)
} catch {
case exc: java.io.IOException =>
println("File not found")
}
var seventhLine: String = _
if (lines != null) {
if (lines.isEmpty) println("too few lines in file")
else seventhLine = lines next
}
if ("" == seventhLine) println("line is empty")</lang>
 
Functional version:
 
<lang scala>val file = try Left(io.Source.fromFile("input.txt")) catch {
case exc => Right(exc.getMessage)
}
val seventhLine = (for(f <- file.left;
line <- f.getLines.toStream.drop(6).headOption.toLeft("too few lines").left) yield
if (line == "") Right("line is empty") else Left(line)).joinLeft</lang>
 
=={{header|sed}}==
Anonymous user