[转帖]Grrovy入门

阅读更多
 Groovy快速入门
1、                集合
1 List (java.util.List)
list = [1, 2, 'hello', new java.util.Date()]
assert list.size() == 4
assert list.get(2) == 'hello'
注意:一切都是对象(数字会自动转换)
2 Map (java.util.Map)
map = ['name':'James', 'location':'London']
assert map.size() == 2
assert map.get('name') == 'James'
3 )遍历集合
list = [1, 2, 3]
for (i in list) { println i }
 
2、  闭包(Closures
l         闭包类似Java 的内类,区别是闭包只有单一的方法可以调用,但可以有任意的参数
closure = { param | println("hello ${param}") }
closure.call("world!")
 
closure = { greeting, name | println(greeting + name) }
closure.call("hello ", "world!")
l         闭包用“{} ”括起,“| ”前面是参数,后面是处理语句,使用call 调用
l         第一个例子演示了在字符串内使用参数的形式:${param}
l         第二个例子演示了多参数形式:用“,”分隔参数
l         如果只有一个参数,可以不写,而使用缺省的参数“it ”,如下面的例子:
closure = { println "hello " + it }
closure.call("world!")
 
3、 each
l         遍历集合,逐个传递给闭包
[1, 2, 3].each { item | print "${item}-" }
l         上面例子的输出结果是:1-2-3-
 
4、 collect
l         遍历集合,逐个传递给闭包,处理后的结果返回给对应的项
value = [1, 2, 3].collect { it * 2 }
assert value == [2, 4, 6]
 
5、 find
l         根据闭包断言,返回集合中找到的第一个项目
value = [1, 2, 3].find { it > 1 }
assert value == 2
 
6、 findAll
l         根据闭包断言,返回集合中所有找到的项目
value = [1, 2, 3].findAll { it > 1 }
assert value == [2, 3]
 
7、 inject
l         遍历集合,第一次将传递的值和集合项目传给闭包,将处理结果作为传递的值,和下一个集合项目传给闭包,依此类推
value = [1, 2, 3].inject('counting: ') { str, item | str + item }
assert value == "counting: 123"
 
value = [1, 2, 3].inject(0) { count, item | count + item }
assert value == 6
 
8、 every
l         如果集合中所有项目都匹配闭包断言,就返回true ,否则返回false
value = [1, 2, 3].every { it < 5 }
assert value
 
value = [1, 2, 3].every { item | item < 3 }
assert ! value
 
9、 any
l         如果集合中任何项目匹配闭包断言,就返回true ,否则返回false
value = [1, 2, 3].any { it > 2 }
assert value
 
value = [1, 2, 3].any { item | item > 3 }
assert value == false
 
10、              min/max
l         返回集合中的最小/ 最大项目(对象必须可比较)
value = [9, 4, 2, 10, 5].max()
assert value == 10
value = [9, 4, 2, 10, 5].min()
assert value == 2
value = ['x', 'y', 'a', 'z'].min()
assert value == 'a'
 
11、              join
l         连接集合中的值成一个字符串
value = [1, 2, 3].join('-')
assert value == '1-2-3'
 
12、              yield
l         Python Ruby 中通过yield 语句创建“yield ”风格的iterators ,在Groovy 同样有效,只是使用的是闭包
class Foo{
 
       static void main(args) {
              foo = new Foo()
              for (x in foo.myGenerator) {
                print("${x}-")
              }
       }
 
       myGenerator(Closure yield) {
              yield.call("A")
              yield.call("B")
              yield.call("C")
       }
}
l         例子的输出结果是:A-B-C-
l         Cloures 原型可以省略,call 和括号同样可选,这样更象Python/Ruby
class Foo {
       myGenerator(yield) {
              yield "A"
              yield "B"
              yield "C" 
       }
 
       static void main(args) {
              foo = new Foo()
              foo.myGenerator { println "Called with ${it}" }
       }
}

你可能感兴趣的:(Groovy,Python,Ruby,C,C++)