Java 8 method references: provide a Supplier capable of supplying a parameterized result

mdo picture mdo · Apr 7, 2014 · Viewed 117.1k times · Source

I'd like to use

java.util.Optional.orElseThrow()

with an Exception type that asks for a constructor parameter. Something like this:

.orElseThrow(MyException::new(someArgument)) // obviously NOT working

Is there a way to create a Supplier that passes my argument value in?

Answer

Louis Wasserman picture Louis Wasserman · Apr 7, 2014

Sure.

.orElseThrow(() -> new MyException(someArgument))