A simple Scala Try, Success, Failure example (reading a file)

Sorry, I don’t have much free time these days, so without any discussion, here’s a simple Scala Try, Success, and Failure example:

import scala.io.Source
import scala.util.{Try,Success,Failure}

object Test extends App {

    def readTextFile(filename: String): Try[List[String]] = {
        Try(Source.fromFile(filename).getLines.toList)
    }

    val filename = "/etc/passwd"
    readTextFile(filename) match {
        case Success(lines) => lines.foreach(println)
        case Failure(f) => println(f)
    }

}

As a brief description, this code prints the lines from the /etc/passwd file if there are no problems, and will print an exception like this if there are problems, such as trying to read the lines from a file named Foo.bar that doesn't exist:

java.io.FileNotFoundException: Foo.bar (No such file or directory)

Note that readTextFile returns this type:

Try[List[String]]

Where a simpler file-reading method will return List[String], it also has the potential to throw an exception, which creates a lot of problems for consumers of the method. So instead of throwing an exception, this method wraps the List[String] in a Try, which gives you the Try[List[String]].

I’ll try to write more on this another time, but for today I just wanted to share the source code in case anyone needs a simple Try/Success/Failure example. In the meantime, see the scala.util.Try documentation for more information.

(One thing you should get from this example is that Try/Success/Failure is an alternative to using Option/Some/None. Specifically, Failure returns whatever text you want from your method when the code in the method fails. In the example shown, Failure contains the exception information from when the given file doesn’t exist, or there is some other problem with the reading the file.)