Guava Deployment Optional in one expression

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.

+6
source share
1 answer

This is not so, because we feel that the anonymous awkwardness class for writing Closure is more inconvenient and less readable - at least in Java, not necessarily in Scala, than the local variable and the if statement that you are already using.

However, another alternative

 for (Foo x : someExpensiveOperation().asSet()) { // do stuff with x } 

Note that asSet is required asSet - Optional very consciously does not implement Iterable .

+7
source

All Articles