MattHicks.com

Programming on the Edge

Learning Scala: scala.Either

Published by Matt Hicks under , on Thursday, October 21, 2010
I would consider myself pretty competent with Scala at this point, but there is still so much I have yet to learn. Something I always used to do in Java was to work my way one class at a time through the JavaDocs of the language I am attempting to do with Scala now as well.

I've just run across the Either class in the ScalaDocs and really like the idea.


The idea is that you may have two different return types that may result from one method. Classically that is solved with all sorts of hackery or returning the common superclass to the two and then doing an instanceof check, but in Scala the Either class provides a much more elegant solution:

object Test {
 def main(args: Array[String]): Unit = {
  numOrString("5") match {
   case Left(s) => println("String: " + s)
   case Right(i) => println("Integer: " + i)
  }
 }
 
 def numOrString(s: String) = {
  try {
   Right(s.toInt)
  } catch {
   case exc: NumberFormatException => Left(s)
  }
 }
}

I'm not really sure how practical this example I wrote is, but my method "numOrString" takes in a String and attempts to convert it to an Int. If it can return an Int it does so or it returns a String. By use of the Left and Right subclasses of Either you can define which type of result you are sending back. Finally, with Scala's awesome matching you can easily determine which type of result you got.

2 comments:

Przemek Pokrywka said... @ October 22, 2010 at 2:36 PM

Probably you are willing to know about a convention, that deals with usage of Left and Right. It advises you to put the expected result (positive case) in the Right, and the other (negative case) in the Left. So your example would need to be changed to follow that convention.

I found out about the convention at one of Scala User Forum pages - first comment of Stefan Langer: "It can be used as a error reporting function like in Haskell with left bearing the error and right bearing the expected value".

Matt Hicks said... @ October 22, 2010 at 3:42 PM

Przemek, thanks for that tip. I changed the code to reflect that convention.

Post a Comment