码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-17 02:21:06      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:



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

标签:

原文地址:http://my.oschina.net/doctor2014/blog/387723

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!