首页 > Java > java教程 > 正文

Confusion Around Method Referencing

Patricia Arquette
发布: 2024-09-23 06:21:14
原创
480 人浏览过

Confusion Around Method Referencing

Method references in Java provide a way to refer to methodsor constructorswithout invoking them explicitly. They can be thought of as a shorthand for writing simple lambda expressions.

Majorly method referencing can either be static or related to an instance:

Integer::sum;
System.out::println;
登录后复制

These are examples of static method references (also known as bound referencing).

However, consider this:

String::concat
登录后复制

Here, concatis not a static method, so how is this working? This is an example of unbound referencing. The compiler understands that this is an instance method reference based on how our code is written. This makes it possible to simplify method calls like this.

The way we write our code determines these types of references (especially unbound ones). Taking concatas an example:

((a, b) -> a + b, "Hello", "World");
// ----------------Is same as -------------
((a, b) -> a.concat(b), "Hello", "World"); // This one could be replaced by mehod referencing

// ----------------Alternative-------------

(String::concat, "Hello", "World");

/* The use of 'a' as the first parameter and calling `concat `of 'a' itself 
gives the compiler an idea of how it should decode `String::concat`*/
登录后复制

So, instead of writing out a full lambda, we can simplify with a method reference.

Keep Learning ?

以上是Confusion Around Method Referencing的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板