Read a specific line from a file: Difference between revisions

Content added Content deleted
Line 1,521: Line 1,521:


=={{header|Scala}}==
=={{header|Scala}}==
===Discussion===
The code will throw a <tt>NoSuchElementException</tt> if the file doesn't have 7 lines.
The code will throw a <tt>NoSuchElementException</tt> if the file doesn't have 7 lines.


<lang scala>val lines = io.Source.fromFile("input.txt").getLines
<lang scala>val lines = io.Source.fromFile("input.txt").getLines
val seventhLine = lines drop(6) next</lang>
val seventhLine = lines drop(6) next</lang>
===Imperative version===

Solving the task to the letter, imperative version:
Solving the task to the letter, imperative version:


Line 1,541: Line 1,542:
}
}
if ("" == seventhLine) println("line is empty")</lang>
if ("" == seventhLine) println("line is empty")</lang>
===Functional version (Recommanded)===

Functional version:

<lang scala>val file = try Left(io.Source.fromFile("input.txt")) catch {
<lang scala>val file = try Left(io.Source.fromFile("input.txt")) catch {
case exc => Right(exc.getMessage)
case exc => Right(exc.getMessage)