Java 8 - why they provided method references?

点点圈 提交于 2021-02-16 14:46:10

问题


What is better in calling

names.stream().forEach(System.out::println);

Than

names.stream().forEach(n -> System.out.println(n));

Despite the fact you have to write less code? Are there any other advantages of introducing method references in Java 8?


回答1:


Despite the fact you have to write less code? Are there any other advantages of introducing method references in Java 8?

Having to write less code is enough of an advantage to consider introducing a language feature. There is a similar feature in C#, called method groups, that makes it easier to write code that uses delegates. Lambdas are shorthand for anonymous classes, and anonymous classes could be considered shorthand for named classes. One could legitimately call them "syntactic sugar", yet all these features help you write less code.

In addition to letting you shorten the code, the feature has a potential of helping designers of Java compiler generate more efficient code. For example, it might be possible to avoid generating a brand-new type for each lambda wrapping a method reference.




回答2:


Well, one advantage above just writing less code is, that the first example doesn't have to be aware of the parameters, as long as the implementation of that functional interface has the same signature (-> is correct) your code get's compiled.

If the signature of the the functional interface changes and the signature of the implementation changes analogously these changes only need to be applied there and not on that glue code.



来源:https://stackoverflow.com/questions/28136014/java-8-why-they-provided-method-references

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