Note that there are some explanatory texts on larger screens.

plurals
  1. POUnwrapping a Guava Optional in a single expression
    primarykey
    data
    text
    <p>As a Scala developer who also works in <code>GWT</code>, I welcome the addition of <code>Optional</code> to Guava.</p> <p>One of our most common use cases of <code>Optional</code> is when returning optional values from methods (as suggested by the answer to <a href="https://stackoverflow.com/questions/9561295/whats-the-point-of-guavas-optional-class">What&#39;s the point of Guava&#39;s Optional class</a>.</p> <p>In scala, I often write code like this:</p> <pre><code>def someExpensiveOperation(params: Type): Option[ResultType] = ... someExpensiveOperation(params).foreach({ val =&gt; doSomethingWithVal (val) }) </code></pre> <p>Guava's Option does not seem to allow anything more elegant than something like this:</p> <pre><code>Optional&lt;MyType&gt; optionalResponse = someExpensiveOperation(params); if (optionalResponse.isPresent()) { doSomethingWithVal(optionalResponse.get()) } </code></pre> <p>The local variable is redundant, and it requires repeating a pattern which could be abstracted (the <code>if (optional.isPresent()) { doSomethingWith(optional.get()) }</code> ).</p> <p>The other option would be to call the method which returns an <code>Optional</code> twice:</p> <pre><code>if (someExpensiveOperation(params).isPresent()) { doSomethingWithVal(someExpensiveOperation(params).get()) } </code></pre> <p>But that is clearly undesirable, since it invoked an expensive operation multiple times unnecessarily.</p> <p>I'm curious how other people have handled this very-common case (perhaps by writing a static utility method like <code>&lt;T&gt;useIfPresent(Optional&lt;T&gt; val, Closure&lt;? super T&gt; closure)</code>?) or if anyone has found more elegant solutions.</p> <p>Also, if anyone knows why a method like <code>Optional.foreach(Closure&lt;? super T&gt; closure)</code> (but hopefully better named) was omitted, I would be curious to hear the rationale.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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