Skip to content

Instantly share code, notes, and snippets.

@jnape
Last active March 12, 2016 06:16
Show Gist options
  • Save jnape/8358e9a9d7985d49046e to your computer and use it in GitHub Desktop.
Save jnape/8358e9a9d7985d49046e to your computer and use it in GitHub Desktop.
Java8 invokeinterface type-unification bug
package example;
import java.util.Optional;
class Foo {}
interface Bar {
String barMethod();
}
public class TypeUnifailcation extends Foo implements Bar {
@Override
public String barMethod() {
return "now you see me...";
}
public static <T extends Foo & Bar> void win(T t) {
Optional.of(t)
.map(x -> x.barMethod()) // invokestatic to anonymous synthetic lambda
.ifPresent(System.out::println);
}
public static <T extends Foo & Bar> void alsoWin(T t) {
Optional.<Bar>of(t)
.map(Bar::barMethod) // invokeinterface with type specified by parametricity (Bar)
.ifPresent(System.out::println);
}
public static <T extends Foo & Bar> void fail(T t) {
// might as well go ahead and compile successfully
// and just produce invalid byte code
Optional.of(t)
.map(Bar::barMethod) // invokeinterface with wrong type (Foo)
.ifPresent(System.out::println);
}
public static void main(String... args) {
TypeUnifailcation example = new TypeUnifailcation();
win(example);
alsoWin(example);
fail(example);
}
}
@jnape
Copy link
Author

jnape commented Mar 12, 2016

Exactly.

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