Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The snippet you posted seems very contrived. You use Either in a situation where:</p> <ol> <li>It's not enough to just know the data isn't available.</li> <li>You need to return one of two distinct types.</li> </ol> <p>Turning an exception into a Left is, indeed, a common use case. Over try/catch, it has the advantage of keeping the code together, which makes sense if the exception is <em>an expected result</em>. The most common way of handling Either is pattern matching:</p> <pre><code>result match { case Right(res) =&gt; ... case Left(res) =&gt; ... } </code></pre> <p>Another interesting way of handling <code>Either</code> is when it appears in a collection. When doing a map over a collection, throwing an exception might not be viable, and you may want to return some information other than "not possible". Using an Either enables you to do that without overburdening the algorithm:</p> <pre><code>val list = ( library \\ "books" map (book =&gt; if (book \ "author" isEmpty) Left(book) else Right((book \ "author" toList) map (_ text)) ) ) </code></pre> <p>Here we get a list of all authors in the library, <em>plus</em> a list of books without an author. So we can then further process it accordingly:</p> <pre><code>val authorCount = ( (Map[String,Int]() /: (list filter (_ isRight) map (_.right.get))) ((map, author) =&gt; map + (author -&gt; (map.getOrElse(author, 0) + 1))) toList ) val problemBooks = list flatMap (_.left.toSeq) // thanks to Azarov for this variation </code></pre> <p>So, basic Either usage goes like that. It's not a particularly useful class, but if it were you'd have seen it before. On the other hand, it's not useless either.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload