Created
March 4, 2018 07:12
-
-
Save benjiman/39cdff62bd4f9e0203e72ca84571bc6f to your computer and use it in GitHub Desktop.
var and passing to methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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