我是靠谱客的博主 友好书本,这篇文章主要介绍java闭包lambda,闭包在groovy vs闭包在java 8(lambda表达式)?,现在分享给大家,希望可以做个参考。

Given doSomething(Function foo) { println foo(2) }

Groovy: doSomething( { it*it } as Function )

Java: doSomething( (x) -> x*x )

Is there any difference between the two?

解决方案

In Java Lambda Expressions there is no way to refer to the parameters of the lambda expressions by default name. There is something on similar lines in Groovy I think it is "it".

In Java Lambda expressions represent a convenient way to implement Single Abstract Method classes/interfaces. So if you have to create a lambda expression for something, you got to have a SAM interface defined for it.

In Java, Lambda expressions can capture only those variable which are effectively final.

In Java, there is an alternate way to represent a Lambda expression by using something called Method References. So if you have some lambda expressions like {() -> new MyObject();} it can be written as MyObject::new. I think not all lambda expressions can be represented by using Method References.

I dont think it would be ideal to compare the lambda expression support in Java 8 with that of more mature Groovy or Scala support. This is the first step for Java to introduce lambda expressions so going forward we can expect to have more mature support for lambda expressions.

最后

以上就是友好书本最近收集整理的关于java闭包lambda,闭包在groovy vs闭包在java 8(lambda表达式)?的全部内容,更多相关java闭包lambda,闭包在groovy内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(105)

评论列表共有 0 条评论

立即
投稿
返回
顶部