Composition of method reference

天涯浪子 提交于 2019-12-04 23:03:06
Chris Jester-Young

As Brian Goetz (project lead for Java lambdas) says, "Lambda expressions have no intrinsic type" (which applies to method references too). This is why you need to cast (or assign) to type Function before its methods become available.

The reason Eclipse shows different error messages from the JDK compiler (javac) is that Eclipse uses its own Java compiler, called ecj, which is a totally different program from javac. This is, BTW, why Eclipse can run on the JRE, without needing a full JDK install.

You can get away without type casts or temporary variables if you create a static helper method (where all functions are parameters rather than method invocation receivers):

static <T,V,R> Function<V, R> chain(
    Function<? super V, ? extends T> f1, Function<? super T, R> f2) {

    return f2.compose(f1);
}

Then you can simply say:

int twelve = methods.operate(1, chain(MyMethods::triple, MyMethods::quadruple));

however, keep in mind that chaining method references this way is neither shorter in source code nor more efficient at runtime compared to a simple lambda expression:

int twelve = methods.operate(1, i -> quadruple(triple(i)));

Note how the last solution does not require type casts, additional variables nor helper methods. Method references are a good tool if you have an already existing method that fits where a function is required but composing a function out of multiple method references is not really useful (in most cases).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!