I think the answer above has it almost right, but I would just encapsulate a Supplier inside of an Optional. Then specify in your documentation that the call to Supplier.get() actually performs the expensive operation.
For example, this is in my code:
<T> Optional<Supplier<T>> findInstance();
When used, I can just check if it exists by doing this:
if (findInstance().isPressent()) { /* do something */ }
No call to Supplier.get() therefore we don't perform the heavy operation.
We can also do something like this, to actually perform the operation conditionally:
findInstance().ifPresent(supplier -> supplier.get().foo());
That will perform the heavy operation explicitly when you call "supplier.get()"
For the sake of clarity, you could create a special interface w/ a JavaDoc tag to make it abundantly clear:
/**
* An on-demand loader which will read objects from disk.
**/
@FunctionalInterface
public interface Loader<T> {
/**
* Returns an newly-loaded instance of T from disk.
**/
T load();
}
This way you explicitly name the method "load" making the intent a little more clear.
java.util.Optional
(not Guava) -Optional
isfinal
, and doesn't already expose such behaviour. So there's no way to achieve this without modifying your API. – Armenianjava.util.Optional
it's pretty clear this behavior is not supported in Java 8 nor 9 (yet). – Gulch