I wonder if someone could explain the following weirdness to me. I'm using Java 8 update 11.
Given this method
private <F,T> T runFun(Function<Optional<F>, T> fun, Optional<F> opt) {
return fun.apply(opt) ;
}
If I first construct a function Object, and pass that in to the method above, things compile.
private void doesCompile() {
Function<Optional<String>, String> fun = o -> o.orElseThrow(() -> new RuntimeException("nah"));
runFun(fun, Optional.of("foo"));
}
But, if I inline the function as a lambda, the compiler says
unreported exception X; must be caught or declared to be thrown
private void doesNotCompile () {
runFun(o -> o.orElseThrow(() -> new RuntimeException("nah")), Optional.of("foo"));
}
Update: Turns out the error message was abbreviated by maven. If compiled directly with javac, the error is:
error: unreported exception X; must be caught or declared to be thrown
runFun(o -> o.orElseThrow(() -> new RuntimeException("nah")), Optional.of("foo"));
^
where X,T are type-variables:
X extends Throwable declared in method <X>orElseThrow(Supplier<? extends X>)
T extends Object declared in class Optional
Also see here for runnable test code.
o.<RuntimeException>orElseThrow(()...
solves the issue, however, this should not be necessary. (I think a similar issue was reported in another stackoverflow question a while ago, but I did not find it right now...) – Marco13