int version = 1
Boolean isDebug = truedef language = 'groovy'def message = "Hello from ${language + 1}, the result is ${isDebug}."task hello {doLast{println message }
}
復制代碼
上面代碼的執行輸出是:
> Task :hello
Hello from groovy1, the result is true.
復制代碼
2.2 List
因為在 Groovy 中沒有定義任何集合類,所以 Groovy 中的 List 使用的是 JDK 中的 java.util.List
def message = 'message'def printMessage () {println message
}void printName(String name) {println name
}void printPerson(String name, age) {println "The name is ${name} and the age is ${age}"
}task helloFunction {doLast {println printName('xiaoming')printPerson 'xiaoming', 20// println printMessage() 會執行異常}
}
復制代碼
輸出結果如下所示:
> Task :app:helloFunction
xiaoming
null
The name is xiaoming and the age is 20
復制代碼
// 閉包可以訪問閉包之外的變量def message = 'closure is good'def printMessage = {println "The message is '${message}'"
}// 閉包實際上是一個 `groovy.lang.Closure` 類
Closure<Boolean> booleanClosure = {return it == 'xiaoming'
}// 閉包可以省略參數,默認有一個 `it` 的參數def testClosure = {println "I am a closure, the params is ${it}."
}// 閉包可以有多個參數,參數可以指定類型,也可以不指定類型def testClosureParams = { name, int age ->println "I am a closure, the params is ${name}."
}// 閉包可以作為另一個閉包的參數def paramsClosure = { name, closure ->if (closure(name)) {println 'The input name is xiaoming'} else {println 'The input name is not xiaoming'}
}task helloClosure {doLast {printMessage()println booleanClosure('xiaoming')println booleanClosure('test')// 閉包的三種調用方式testClosure 'xiaoming'testClosure.call('xiaoming')testClosure('xiaoming')testClosureParams('xiaoming', 20)// 閉包 booleanClosure 作為閉包 paramsClosure 的參數paramsClosure('xiaoming', booleanClosure)paramsClosure('test', booleanClosure)// 可以在調用閉包的時候才去定義參數閉包的定義,使用非常方便簡潔paramsClosure('xiaoming', { name ->name.toUpperCase() == 'XIAOMING'})}
}
復制代碼
輸出如下所示
> Task :app:helloClosure
The message is 'closure is good'truefalse
I am a closure, the params is xiaoming.
I am a closure, the params is xiaoming.
I am a closure, the params is xiaoming.
I am a closure, the params is xiaoming.
The input name is xiaoming
The input name is not xiaoming
The input name is xiaoming
復制代碼