Skip to content

Instantly share code, notes, and snippets.

@benjiman
Created March 4, 2018 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjiman/39cdff62bd4f9e0203e72ca84571bc6f to your computer and use it in GitHub Desktop.
Save benjiman/39cdff62bd4f9e0203e72ca84571bc6f to your computer and use it in GitHub Desktop.
var and passing to methods
package example;
public class Example {
public static void main(String... args) {
var duck = (Quacks & Waddles) Mixin::create;
// this works as the intersection type is inferred.
methodThatDoesDucklikeThings(duck);
var ducklikeException = new RuntimeException("runtime ex with message") {
void quack() {
System.out.println("Quack");
}
void waddle() {
System.out.println("Waddle");
}
};
// this works as Throwable is a supertype
log(ducklikeException);
// this would not work as the bounds don't match
// methodThatDoesDucklikeThings(ducklikeException);
// this does work as Quack is structurally equivalent to the method reference
quack(ducklikeException::quack);
// as does quacking an actual duck
quack(duck);
}
static <T extends Quacks & Waddles> void methodThatDoesDucklikeThings(T ducklike) {
ducklike.quack();
ducklike.waddle();
}
static <T extends Throwable> void log(T t) {
System.out.println(t.getMessage());
}
static <T extends Quacks> void quack(T ducklike) {
ducklike.quack();
}
interface Quacks extends Mixin {
default void quack() {
System.out.println("Quack");
}
}
interface Waddles extends Mixin {
default void waddle() {
System.out.println("Waddle");
}
}
interface Mixin {
void __noop__();
static void create() {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment