Here's an example from "Programming Scala" (O'Reilly), page 158 in Chapter 7, "The Scala Object System", which we adapted from Daniel Scobral's blog (http://dcsobral.blogspot .com/2009/06/catching-exceptions.html):
// code-examples/ObjectSystem/typehierarchy/either-script.scala
def exceptionToLeft[T](f: => T): Either[java.lang.Throwable, T] = try { Right(f)
} catch {
}
case ex => Left(ex)
def throwsOnOddInt(i: Int) = i % 2 match { case 0 => i
}
case 1 => throw new RuntimeException(i + " is odd!")
for(i <- 0 to 3) exceptionToLeft(throwsOnOddInt(i)) match {
}
case Left(ex) => println("exception: " + ex.toString) case Right(x) => println(x)
Either is a built-in type and this idiom is common in some functional languages as an alternative to throwing an exception. Note that you Left and Right are subtypes of Either. Personally, I wish the type were named "Or", so you could write "Throwable Or T".