概述
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 vs闭包在java 8(lambda表达式)?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复