1

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

Ralf Wagner
  • 1,467
  • 11
  • 19
jdhalleine
  • 13
  • 1
  • 3
  • Can't you just use `Predicate`s? – VLAZ Mar 07 '20 at 14:21
  • You are not questioning some concrete question to achive some concrete results. "the best way" is too opinion based and is not how stackoverflow works. Please think up some concrete things or areas you want to improve in your code and ask the qeustion. – Superluminal Mar 07 '20 at 14:30
  • @VLAZ can you explain me how can i use Predicate ? – jdhalleine Mar 07 '20 at 14:46

1 Answers1

3

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")));
ernest_k
  • 44,416
  • 5
  • 53
  • 99