lambda - Does a method reference in Java 8 have a concrete type and if so, what is it? -
this question has answer here:
this question pretty closely related another one. however, feel accepted answer question not quite definitive.
so, is type of method reference in java 8? here's little demonstration of how method reference can "cast" (lifted?) java.util.function.function
:
package java8.lambda; import java.util.function.function; public class question { public static final class greeter { private final string salutation; public greeter(final string salutation) { this.salutation = salutation; } public string makegreetingfor(final string name) { return string.format("%s, %s!", salutation, name); } } public static void main(string[] args) { final greeter hellogreeter = new greeter("hello"); identity(hellogreeter::makegreetingfor) .andthen(g -> "<<<" + g + ">>>") .apply("joe"); //compilation error: object not function interface // function // .identity() // .apply(hellogreeter::makegreetingfor) // .andthen(g -> "<<<" + g + ">>>") // .apply("joe"); function .<function<string,string>>identity() .apply(hellogreeter::makegreetingfor) .andthen(g -> "<<<" + g + ">>>") .apply("joe"); //compilation error: cannot resolve method 'andthen(<lambda expression>)' // (hellogreeter::makegreetingfor) // .andthen(g -> "<<<" + g + ">>>") // .apply("joe"); // java.lang.invoke.lambdametafactory ??? } private static <i,o> function<i,o> identity(final function<i,o> fun1) { return fun1; } }
so, there less painful (more straight-forward) way of casting method reference compiled/concrete type can passed around?
first of all, method references "are compact, easy-to-read lambda expressions methods have name" (see the java tutorials - method references).
so in fact, asking type of lambda expression. explained in jls §15.27.3 (type of lambda expression).
in short, there 3 compatibilities mentioned:
- assignment context
- invocation context
- casting context
the type of lambda expression or method reference inferred compiler. several contexts can (and must) taken account, java 8 came big enhancements type inference.
the restriction lambda expressions inferred type must functional interface. in fact, equal lambda expressions can have different types regarding context.
Comments
Post a Comment