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



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

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

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

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

Now, consider this lambda expression:this

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

(MyObject myObj) -> myObj.toString()code

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

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 forit

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.

相關文章
相關標籤/搜索