Useful intersection type applications using local type inference

As this blog pointed out, we can now write the following using a local type of output (something as far as I know, this was previously impossible without introducing more code):

public static void main(String... args) { var duck = (Quacks & Waddles) Mixin::create; duck.quack(); duck.waddle(); } 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() {} } 

This question can be either too broad or mainly opinion-based, but are there any useful applications when using these types of intersections?

+7
java type-inference
source share
2 answers

Working with partially unknown types is possible with Java 5, so its silent appeal to your example in Java 8:

 public static void main(String... args) { use((Quacks & Waddles)Mixin::create); } private static <Duck extends Quacks & Waddles> void use(Duck duck) { duck.quack(); duck.waddle(); } 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() {} } 

Thus, the ability to do the same with var in Java 10 also allows you to do the same as before, but with slightly smaller source code. And the ability to do the same thing as before, but with less template code is exactly what var , regardless of whether you use intersection types or not.

+5
source share

You can also do this in java-8:

 static class ICanDoBoth implements Quacks, Waddles { // implement void __noop__(); here... } public static void both(Object b) { // my point here is that you can't declare such a type 'x' Optional.of((Quacks & Waddles) b) .ifPresent(x -> { x.quack(); x.waddle(); }); } 

And name it via: both(new ICanDoBoth());

The thing is, you cannot declare an intersection type variable (well, if var or a variable that was output by the compiler using Optional.of() ).

There are practically a few tips here , but I have never used a variable like intersection in something very useful ...

+3
source share

All Articles