groovy基本语法:

#!/usr/bin/env groovy

// 打印 Hello World
println “Hello world!”

// 变量定义 Variables: You can assign values to variables for later use
def x = 1
println x

x = new java.util.Date()
println x

x = -3.1499392
println x

x = false
println x

x = “Groovy!”
println x

// 列表 Creating an empty list
def technologies = []

/ 添加一个元素到列表中 Adding a elements to the list /
// As with Java
technologies.add(“Grails”)

// 添加多个元素到列表中 Add multiple elements
technologies.addAll([“Gradle”,”Griffon”])

/ 删除列表中元素 Removing elements from the list /
// As with Java
technologies.remove(“Griffon”)

// Subtraction works also
technologies = technologies - ‘Grails’

/ Iterating Lists /
// Iterate over elements of a list
technologies.each { println “Technology: $it”}
technologies.eachWithIndex { it, i -> println “$i: $it”}

/ 元素是否存在判断 Checking List contents /
//Evaluate if a list contains element(s) (boolean)
contained = technologies.contains( ‘Groovy’ )

// Or
contained = ‘Groovy’ in technologies

// 计数 Check for multiple contents
technologies.containsAll([‘Groovy’,’Grails’])

/ 排序 Sorting Lists /

// 在原列表上重新排序 Sort a list (mutates original list)
technologies.sort()

// 排序不影响源列表 To sort without mutating original, you can do:
sortedTechnologies = technologies.sort( false )

/ 字典 Manipulating Lists /

// 替换列表中所有元素 Replace all elements in the list
Collections.replaceAll(technologies, ‘Gradle’, ‘gradle’)

//Shuffle a list
Collections.shuffle(technologies, new Random())

//Clear a list
technologies.clear()

// 字典 Creating an empty map
def devMap = [:]

// 添加新元素 Add values
devMap = [‘name’:’Roberto’, ‘framework’:’Grails’, ‘language’:’Groovy’]
devMap.put(‘lastName’,’Perez’)

// 遍历字典 Iterate over elements of a map
devMap.each { println “$it.key: $it.value” }
devMap.eachWithIndex { it, i -> println “$i: $it”}

// 判断是否为存在key Evaluate if a map contains a key
assert devMap.containsKey(‘name’)

// 判断是否为存在value Evaluate if a map contains a value
assert devMap.containsValue(‘Roberto’)

//Get the keys of a map
println devMap.keySet()

//Get the values of a map
println devMap.values()

//Groovy supports the usual if - else syntax
// if 语句
def x1 = 3

if(x1==1) {
println “One”
} else if(x1==2) {
println “two”
} else {
println “X greater than Two”
}

//Groovy also supports the ternary operator:
def y = 10
def x2 = (y > 1) ? “worked” : “failed”
assert x2 == “worked”

//Instead of using the ternary operator:
//displayName = user.name ? user.name : ‘Anonymous’
//We can write it:
//displayName = user.name ?: ‘Anonymous’

//For loop
//Iterate over a range
def x3 = 0
for (i in 0 .. 30) {
x3 += i
}

//Iterate over a list
x4 = 0
for( i in [5,3,2,1] ) {
x4 += i
}

//Iterate over an array
array = (0..20).toArray()
x5 = 0
for (i in array) {
x5 += i
}

//Iterate over a map
def map = [‘name’:’Roberto’, ‘framework’:’Grails’, ‘language’:’Groovy’]
x6 = 0
for ( e in map ) {
x6 += e.value
}

/
Closures
A Groovy Closure is like a “code block” or a method pointer. It is a piece of
code that is defined and then executed at a later point.
More info at: http://www.groovy-lang.org/closures.html
/

//Example:
def clos = { println “Hello World!” }

println “Executing the Closure:”
clos()

//Passing parameters to a closure
def sum = { a, b -> println a+b }
sum(2,4)

//Closures may refer to variables not listed in their parameter list.
def x7 = 5
def multiplyBy = { num -> num * x7 }
println multiplyBy(10)

// If you have a Closure that takes a single argument, you may omit the
// parameter definition of the Closure
def clos2 = { println it }
clos2( “hi” )

/
Groovy can memoize closure results [1][2][3]
/
def cl = {a, b ->
sleep(3000) // simulate some time consuming processing
a + b
}

mem = cl.memoize()

def callClosure(a, b) {
def start = System.currentTimeMillis()
println mem(a, b)
println “Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs.”
}

callClosure(1, 2)
callClosure(1, 2)
callClosure(2, 3)
callClosure(2, 3)
callClosure(3, 4)
callClosure(3, 4)
callClosure(1, 2)
callClosure(2, 3)
callClosure(3, 4)