1

I've coded that:

Optional.ofNullable(this.cache.get(id))
    .orElseGet(this.referenceService.get(id));

The problem is that this.referenceService.get returns an Optional.

So, I'm getting this compilation message:

The method orElseGet(Supplier<? extends Reference>) in the type Optional<Reference> is not applicable for the arguments (Optional<Reference>)

Any ideas?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
Jordi
  • 20,868
  • 39
  • 149
  • 333

2 Answers2

3

Starting with java 9 you can use Optional.or()

Optional<String> foo = Optional.empty();
Optional<String> bar = Optional.ofNullable("Bar");
System.out.println(foo.or(() -> bar));
baao
  • 71,625
  • 17
  • 143
  • 203
1

If you're using Java 9, you have access to Optional.or, which accepts a Supplier<Optional<T>>.

If not, the below pattern works:

Optional.ofNullable(this.cache.get(id))
    .orElseGet(() -> this.referenceService.get(id)
        .orElseThrow(()-> new RuntimeException("Expected service to return something")));
Ben R.
  • 1,965
  • 1
  • 13
  • 23