The scanned fragment seems very far-fetched. You use either in a situation where:
- Itโs not enough just to know that data is not available.
- You need to return one of two different types.
Turning an exception into a left is indeed a common use case. Compared to try / catch, it has the advantage of keeping the code together, which makes sense if the exception is the expected result. The most common way to process data is to select a template:
result match { case Right(res) => ... case Left(res) => ... }
Another interesting way to handle Either is when it appears in a collection. When you draw a map over a collection, throwing an exception may not be practical, and you might want to return some information other than "impossible." Using Either allows you to do this without overloading the algorithm:
val list = ( library \\ "books" map (book => if (book \ "author" isEmpty) Left(book) else Right((book \ "author" toList) map (_ text)) ) )
Here we get a list of all authors in the library, as well as a list of books without an author. Therefore, we can then process it accordingly:
val authorCount = ( (Map[String,Int]() /: (list filter (_ isRight) map (_.right.get))) ((map, author) => map + (author -> (map.getOrElse(author, 0) + 1))) toList ) val problemBooks = list flatMap (_.left.toSeq) // thanks to Azarov for this variation
So basic Either use goes like this. This is not a particularly useful class, but if you had seen it before. On the other hand, this is not useless either.
Daniel C. Sobral Jul 28 '09 at 17:09 2009-07-28 17:09
source share