快速开始

在开始以前

在开始案例之前,建议你应该先看看:

当然,你也可能希望阅读一些更深层次的内容:

你的首个Groovy程序

//hello.groovy
println "hello, world"
for (arg in this.args ) {
  println "Argument:" + arg;
}
// this is a comment
/* a block comment, commenting out an alternative to above:
this.args.each{ arg -> println "hello, ${arg}"}
*/

请在命令行下执行:

groovy hello.groovy MyName yourName HisName

概述

Groovy类最终被编译成Java字节码,因此Groovy类和Java类是一一对应的。

事实上每一个Groovy类可以被用在普通的Java代码中——要知道在本质上它就是Java类。

也许接触Groovy最容易的途径是学习集合,毕竟Groovy的List类(java.util.List)和Map类(java.util.Map)都是句法中头等重要的类对象,让我们创造一组List对象吧:

def list = [1, 2, 'hello', new java.util.Date()]
assert list.size() == 4
assert list.get(2) == 'hello'
assert list[2] == 'hello'

注意任何东西都是对象了(或者你也可以理解成自动装箱功能在操纵数字的时候发挥作用了)。再来创建Map对象:

def map = ['name':'James', 'location':'London']
assert map.size() == 2
assert map.get('name') == 'James'
assert map['name'] == 'James'

遍历集合也是非常容易的:

def list = [1, 2, 3]
for (i in list) { println i }

一旦你拥有一组集合,你可以使用操纵集合的新利器——闭包。

使用闭包

闭包和Java中的内部类很类似,不同的是闭包可以接受任意类型的参数,你也可以使用任意多的参数:

def closure = { param -> println("hello ${param}") }
closure.call("world!")
 
closure = { greeting, name -> println(greeting + name) }
closure.call("hello ", "world!")

如果没有参数在->算符之前指定,一个名为”it”的默认参数可被使用:

def closure = { println "hello " + it }
closure.call("world!")

闭包使得我们得以用一种更清晰的方式使用集合(array、map、string、文件、SQL连接等等)。

[1, 2, 3].each ({ item -> print "${item}-" })
["k1":"v1", "k2":"v2"].each {key, value -> println key + "=" + value}

注意:如果使用闭包作为最末参数,其定义可在圆括号外完成。因此如下代码是正确的:

def fun(int i, Closure c) {
  c.call(i)
}
 
//将闭包放到()之外
[1, 2, 3].each() { item -> print "${item}-" } // 1-2-3-
fun(123) { i -> println i } // 123
 
//忽略一次()
[1, 2, 3].each ({ item -> print "${item}-" }) // 1-2-3-
 
//完全忽略()
[1, 2, 3].each { item -> print "${item}-" } // 1-2-3-
 
//常规
[1, 2, 3].each(({ item -> print "${item}-" })) // 1-2-3-
 
//使用fun方法完成相同的功能
[1,2,3].each {fun(it,{item -> print "${item}-"})} // 1-2-3-
 
def closure = { i -> println i}
 
//[1, 2, 3].each() closure //错误。闭包重定义了

以下是一组集合和string类的应用:

each

遍历闭包:

[1, 2, 3].each { item -> print "${item}-" }

collect

收集从集合对象中返回的每一项:

def value = [1, 2, 3].collect { it * 2 }
assert value == [2, 4, 6]

find 查找匹配闭包断言的第一项:

def value = [1, 2, 3].find { it > 1 }
assert value == 2

findAll

查找所有匹配闭包断言的项:

def value = [1, 2, 3].findAll { it > 1 }
assert value == [2, 3]

inject

允许你传值给第一个遍历项,将此项结果传给第二项,并以此类推。如下采用此方法实现的计数和一个类似的功能:

def 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
In addition there's 2 new methods for doing boolean logic on some collection...

every

如果所有项都匹配闭包断言的话就返回真:

def value = [1, 2, 3].every { it < 5 }
assert value
 
value = [1, 2, 3].every { item -> item < 3 }
assert ! value

any

如果其中存在任一项匹配闭包断言就返回真:

def value = [1, 2, 3].any { it > 2 }
assert value
 
value = [1, 2, 3].any { item -> item > 3 }
assert value == false

其他方法还有:

max / min

返回集合的最大/最小值——当然其中的对象必须是可比较的:

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'

join

将集合的值用某一个字符串连接起来:

def value = [1, 2, 3].join('-')
assert value == '1-2-3'
 
wiki/getting_started_guide/quick_start.txt · 最后更改: 2008-04-19 13:50 (外部编辑)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki