Reputation: 13
Before Java 8, i got used to writte my code this way
import io.vavr.control.Option;
Option<String> nullableValueA=Option.of("toto");
Option<String> nullableValueB=Option.of(null);
if (nullableValueA.isEmpty() && nullableValueB.isEmpty()){
throw new RuntimeException("Business exception");
}
I'd like to transform this code below in a pure Java functional style with Java API or even vavr API
and doing something like this
nullableValueA.isEmpty()
.and(nullableValueB.isEmpty())
.then(
() -> throw new RuntimeException("Business exception");
)
Any ideas of how writting this code the best way ?
Thanks a lot for your help
Upvotes: 1
Views: 997
Reputation: 45319
If you're on Java 9+, you can use
String value = Optional.ofNullable("<resolve valueA>")
.or(() -> Option.ofNullable("<resolve valueB>"))
.orElseThrow(() -> new RuntimeException("Business exception"));
That will give you the first non-empty value, throwing an exception if both are empty.
The same thing can be achieved on Java 8 using something like:
String value = Optional.ofNullable("<resolve valueA>")
.orElseGet(() -> Optional.ofNullable("<resolve valueB>")
.orElseThrow(() -> new RuntimeException("Business exception")));
Upvotes: 3