One of the things that I recently discovered in Scala is Try and Ether statements. They’re extremely cool to work with!

To Try

In the order I learned about them, I’ll explain what a Try is. It is a method that wraps the incoming and handles all exceptions that come out of it. If an exception comes out of it the value that is represented by the Try will be returned as Failure([exceptionvalue]). If the result was a success then the object Success([result value]) is returned. Pretty cool right? This means you don’t have to setup a Try/Catch everytime that you have an exception thrown. Combined with pattern matching, this will allow for you to simplify your statements that have Try/Catches. Even better: Try:Success is an option.

An example of this is:

class demonstration {
  def getGoogleResults(keyword: String) = {
    var googleClientResult = null
    try {
      val googleClient = new GoogleClient(authKeys)
      googleClientResult = googleClient.query(keyword)
    } catch (exception: Exception) {
      System.err.println(s"Error: $exception")
      throw exception
    }
    System.out.println(s"It found   $ {googleClientResult.size}")
  }

  def getBetterGoogleResults(keyword:String) = {
    val googleClient = new GoogleClient(authKeys)
    val googleResults = Try(googleClient.query(keyword))

    googleResults.success.map(v => System.out.println(s"It found ${v.size}")
      googleResults.failure.map(e => {
      System.err.println(s"Error $e")
      throw e
    })
  }
}

The getGoogleResults method shows the Java style of doing this. The getBetterGoogleResults shows the shorter functional try way of going about this. It reduced a bit of boilerplate and made the code a lot easier to read. Something to note: success and failure coming off of the Try object are Options.

How does this work? (Either it does or it doesn’t)

Try is a case of a language feature called Either in Scala. Either is a way to return two possible non-common objects. In other words, you can return either a String or an Integer from a method. Either uses generics to type each case (the left or the right), and it handles the direction of what object that comes back.

Since there is a possibility of different types, it’s not possible to have a single method to get the results of the try. (That would be possible in Groovy!) You have to work with both possible types (as we showed with the success and failure responses in the example above). Luckily, the left and right values coming off of the Ether are Options, which makes this less painful.

Going back to the Try vs. Either reference: A try is and Either object defined as having a Success and Failure object. The other difference is that Try handles exceptions, and it has special names for success and failure added to the class.

References