You can Either Try or not (Scala: Try, Either)

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

Some of the things that I’ve been up to in the last few months (March-June)

Some of the things that I’ve been up to in the last few months:

  1. I saw Metallica for the first time a few days ago! That was pretty awesome. I would say that was either my third or second best concert that I’ve ever seen. The first best was Rammstein at the Open Air Festival last year.
  2. I learned about Try/Ether in Scala. That’s pretty awesome. Expect a blog post coming out about that
  3. I started doing the X Effect challenge for 50 squats a day over 49 days. So far I’m 40 days in and I’ve only missed 3 days. That’s pretty awesome.
  4. Wearing sunglasses when it’s sunny is a good idea. It helps to prevent your eyes from straining. I feel like I should have learned this a long time ago. Doh.
  5. I’ve been experimenting with turning my phone off while at work and during social events. This has helped my concentration and focus immensely. Although, it has been a learning experience with quick attempts to check the phone.
  6. I’ve taken a hiatus from side projects for the last 4 months. It’s been nice to have a life back and not worry about getting a huge project done.
  7. My parents came up to Chicago and we visited Davenport, IA. We got to see the Mississipi River. 
  8. I got a fantastic new camera: the Lumix LX10. I love the thing. It’s been taking some great pictures.
  9. I’ve recently started planting more house plants. I added more snake plants, bird of paradise, cactus, and an aloe plant. Outside: I replaced a large weed with an annual Lilly.
  10. I learned how to make side cars with the brandy that my friend Erik gave me for my birthday.
  11. I learned about how amazing Oaxacian tamales are. I had these at the Taste of Little Village Festival

I’m sure that I’ve been up to more, but that’s all that comes up to mind