In Java 10, it is possible to declare variables by type inference called var. For example var url = new URL("http://ukiuni.com"); Then, url is type inferred and becomes a URL type variable.
Up to this point, the story ends with "Hey. It's syntactic sugar that can omit the description of variables." However, in Java 10 type inference, "inexpressible types can also be inferred." I will.
.. .. .. I don't know what you're talking about, but I don't know what you're talking about either.
Here is the sample code.
Sample.java
public class Sample{
public static void main(String[] args) {
var ins = (Foo & Bar) ()->{};
ins.foo();
ins.bar();
ins.forFunctionalInterfaceMethod(); //☓ You can call it without implementing it → Corrected by receiving comments. 3 lines above()->{}Is implemented.
ins.toString(); //It is also an Object type.
}
interface Base {
void forFunctionalInterfaceMethod();
}
interface Foo extends Base {
default void foo() {
System.out.println("foo");
}
}
interface Bar extends Base {
default void bar() {
System.out.println("bar");
}
}
}
If you compile and run this in Java 10, you will get the following output.
$ javac Sample.java && java Sample
foo
bar
In other words var ins = (Foo & Bar) ()->{}; Ins is a Foo type, a Bar type, a Base type that is the parent of the interface, and an Object type. This is the intersection type, which is an "inexpressible type". Now you can do something like a dynamic mixin.
.. .. .. In what cases can it be used conveniently? .. .. If you have any insights, please comment.
Recommended Posts