Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Either to process failures in Scala code
    text
    copied!<p><code>Option</code> monad is a great expressive way to deal with something-or-nothing things in Scala. But what if one needs to log a message when "nothing" occurs? According to the Scala API documentation,</p> <blockquote> <p>The Either type is often used as an alternative to scala.Option where Left represents failure (by convention) and Right is akin to Some.</p> </blockquote> <p>However, I had no luck to find best practices using Either or good real-world examples involving Either for processing failures. Finally I've come up with the following code for my own project:</p> <pre><code> def logs: Array[String] = { def props: Option[Map[String, Any]] = configAdmin.map{ ca =&gt; val config = ca.getConfiguration(PID, null) config.properties getOrElse immutable.Map.empty } def checkType(any: Any): Option[Array[String]] = any match { case a: Array[String] =&gt; Some(a) case _ =&gt; None } def lookup: Either[(Symbol, String), Array[String]] = for {val properties &lt;- props.toRight('warning -&gt; "ConfigurationAdmin service not bound").right val logsParam &lt;- properties.get("logs").toRight('debug -&gt; "'logs' not defined in the configuration").right val array &lt;- checkType(logsParam).toRight('warning -&gt; "unknown type of 'logs' confguration parameter").right} yield array lookup.fold(failure =&gt; { failure match { case ('warning, msg) =&gt; log(LogService.WARNING, msg) case ('debug, msg) =&gt; log(LogService.DEBUG, msg) case _ =&gt; }; new Array[String](0) }, success =&gt; success) } </code></pre> <p>(Please note this is a snippet from a real project, so it will not compile on its own)</p> <p>I'd be grateful to know how you are using <code>Either</code> in your code and/or better ideas on refactoring the above code.</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