Skip to content

Instantly share code, notes, and snippets.

@rompetroll
Last active May 13, 2017 06:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rompetroll/667bf46ac0168a92497a to your computer and use it in GitHub Desktop.
Save rompetroll/667bf46ac0168a92497a to your computer and use it in GitHub Desktop.
java8 lambdas and exceptions
import java.util.function.Function;
import java.util.Optional;
public class Compile {
private <F,T> T runFun(Function<Optional<F>, T> fun, Optional<F> opt) {
return fun.apply(opt) ;
}
public void foo() {
Function<Optional<String>, String> fun = o -> o.orElseThrow(() -> new RuntimeException("nah"));
runFun(fun, Optional.of("foo"));
}
}
import java.util.function.Function;
import java.util.Optional;
public class NoCompile {
private <F,T> T runFun(Function<Optional<F>, T> fun, Optional<F> opt) {
return fun.apply(opt) ;
}
public void foo() {
runFun(o -> o.orElseThrow(() -> new RuntimeException("nah")), Optional.of("foo"));
}
}
java -version
|java version "1.8.0_11"
|Java(TM) SE Runtime Environment (build 1.8.0_11-b12)
|Java HotSpot(TM) 64-Bit Server VM (build 25.11-b03, mixed mode)
javac Compile.java
javac NoCompile.java
|NoCompile.java:10: 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
|1 error
@zarinfam
Copy link

This was a type inference bug, It was partially resolved in 1.8.0_92 release. please update your JDK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment