JAVA8 之 Method References-Java in a Nutshell, 6th

來源:互聯網
上載者:User

標籤:



JAVA8 的函數引用和 lambda運算式的關係=>函數引用是一種簡化的 lambda運算式,只給出現有的函數,參數和傳回值編譯器推斷去吧.

 其實這文法和 lambda運算式正好相反, lambda運算式表示匿名方法,就是沒有函數名,只給出參數和方法體.那麼現有的函數就派上用場了,現有的函數有方法名,給出方法名,參數和方法體都已經有了,由編譯器推斷出.

註:java中的方法不能獨立存在,必須包含在類型中,這就是 lambda運算式 @FunctionalInterface的限制.

Recall that we can think of lambda expressions as methods that don’t have names.

Now, consider this lambda expression:

// In real code this would probably be shorter because of type inference

(MyObject myObj) -> myObj.toString()

This will be autoconverted to an implementation of a @FunctionalInterface that

has a single nondefault method that takes a single MyObject and returns String.

However, this seems like excessive boilerplate, and so Java 8 provides a syntax for

making this easier to read and write:

MyObject::toString

This is a shorthand, known as a method reference, that uses an existing method as a

lambda expression. It can be thought of as using an existing method, but ignoring

the name of the method, so it can be can used as a lambda, and autoconverted in the

usual way.



JAVA8 之 Method References-Java in a Nutshell, 6th

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.