1. Closure Package
Closures are a handy feature provided by many dynamic languages, something like an inner class in Java, except that there is only one method in the closure, but this method can have any number of arguments.
Java code
This code will output "Hello World".
1. def closure = { param -> println("hello ${param}") }
2. closure.call("world!")
The closure package "{}" is enclosed, "->" is preceded by a parameter, followed by a processing statement, can be invoked using call, or it can be executed directly after "{}" by using "()".
Closures can have more than one parameter, and each parameter is separated by ",". If there is only one argument can be omitted without writing, you can use the keyword "it" to represent.
We can write the above example as follows:
Java code
closure = { println("hello ${it}") }('world')
Or
Java code
1. closure = { param1,param2->
2. println(param1+param2) }('hello ','world')
Several of the above are written out "Hello World".
2. Collection
(1) List
Java code
1. def list = [1, 2, 'hello', new java.util.Date()]
2. assert list.size() == 4
3. assert list[1]==2
4. assert list.get(2) == 'hello'
(2) Map
Java code
1. def map = ['name':'James', 'location':'London']
2. assert map.size() == 2
3. assert map.get('name') == 'James'
4. assert map['location']=='London'
(3) Circulation
Java code
1. def list = [1, 2, 3]
2. for (i in list) {
3. print i
4. }
5. println()
6.
7. list.each{item->
8. print item
9. }
10. println()
11.
12. ['name':'yanhua','addr':'beijing'].each{println it}
13. ['name':'yanhua','addr':'beijing'].each{key,value->println "${key} ^_^ ${value}"}
The results of the above operation are as follows:
123
123
Name=yanhua
Addr=beijing
Name ^_^ Yanhua
Addr ^_^ Beijing