As a Scala developer who also works in GWT , I welcome the addition of Optional to Guava.
One of our most common use cases for Optional is to return optional values ββfrom methods (as suggested in response to What is the point of an additional Guava class .
In scala, I often write code like this:
def someExpensiveOperation(params: Type): Option[ResultType] = ... someExpensiveOperation(params).foreach({ val => doSomethingWithVal (val) })
The Guava variant does not seem to allow anything more elegant than something like this:
Optional<MyType> optionalResponse = someExpensiveOperation(params); if (optionalResponse.isPresent()) { doSomethingWithVal(optionalResponse.get()) }
The local variable is redundant and requires repeating the pattern, which can be abstracted ( if (optional.isPresent()) { doSomethingWith(optional.get()) } ).
Another option is to call a method that returns Optional twice:
if (someExpensiveOperation(params).isPresent()) { doSomethingWithVal(someExpensiveOperation(params).get()) }
But this is clearly undesirable, since it caused an expensive operation several times unnecessarily.
I'm curious how other people handled this very common case (perhaps by writing a static utility method like <T>useIfPresent(Optional<T> val, Closure<? super T> closure) ?), Or if someone found more elegant solutions.
Also, if anyone knows why a method like Optional.foreach(Closure<? super T> closure) (but hopefully a better named one) was omitted, I would be interested to hear the rationale.
source share