程式扎記: [ GroovyGN ] Turn Methods into Closures

標籤

2015年2月24日 星期二

[ GroovyGN ] Turn Methods into Closures

Source From Here
Preface
Groovy supports closures and they are very useful when we create Groovy applications. For example we can pass closures as arguments to methods to execute them. We can create closures ourselves, but we can also convert a method to a closure with the .& operator. And we can use the converted method just like a normal closure. Because Groovy can use Java objects we can also convert a Java method into a closure.

How-To
Let's start with a simple Java class:
  1. public class JavaObject {  
  2. public static void javaSays(final String s) {  
  3.   System.out.println("Java says: Hello " + s + "!");  
  4. }  
  5. }  
With the following script we use this Java class and convert the javaSays method to a closure:
  1. // Simple list with names.  
  2. def names = ['groovy''grails''mrhaki']  
  3.   
  4. // Simple closure.  
  5. names.each { println 'Normal closure says: Hello ' + it + '!' }  
  6.   
  7. // Groovy method to convert to closure.  
  8. def groovySays(s) {  
  9.     printf("Groovy says: Hello ${s}!\n")  
  10. }  
  11. // Use .& syntax to convert method to closure.  
  12. names.each(this.&groovySays)  
  13.   
  14. // Convert Java method to closure and use it.  
  15. def javaSays = JavaObject.&javaSays  
  16. names.each javaSays  
If we run this script we get the following output:
Normal closure says: Hello groovy!
Normal closure says: Hello grails!
Normal closure says: Hello mrhaki!
Groovy says: Hello groovy!
Groovy says: Hello grails!
Groovy says: Hello mrhaki!
Java says: Hello groovy!
Java says: Hello grails!
Java says: Hello mrhaki!

Supplement
[ User Guide ] Closure
[ In Action ] Working with closures - The case for closures
[ In Action ] Working with closures - Declaring closures
The third way of declaring a closure is to reuse something that is already declared: a method. Methods have a body, optionally return values, can take parameters, and can be called. The similarities with closures are obvious, so Groovy lets you reuse the code you already have in methods, but as a closure. Referencing a method as a closure is performed using the reference .& operator...


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!