Groovy语言学习
基本语法
print,println,printf
//打印
println(1)
print(1)
println()
//可以不加括号
println "hello"
定义变量
//强类型
int a = 5
//弱类型。会根据赋值自动解析数据类型
def a = 5
println(a.class) //class java.lang.Integer
方法定义
//定义方法
def test(def a,def b){
println(a+b)
}
test(5,6) // 11
test("5","6")// '56'
test("5",6) //'56'
def test2(def a){
def b = a? 'true':'false'
println(b)
}
test2(true) // true
test2(10) //true
test2("") //false
test2("10") //true
list和map
定义map使用的是[]
不是{}
使用for(i in map)
这里的i是key:value
//列表的定义
def list = ["1","2"]
//遍历
for (i in list){
println(i)
} // 1 2
for (j in [0,1]){
println(list[j]) //list[i] 取值
} // 1 2
//定义map集合
def map = ["Chinese":50,"Math":25]
println(map) //["Chinese":50,"Math":25]
println(map.keySet()) // [Chinese, Math]
println(map.values()) // [50,25]
println(map.Chinese) // 50
println(map.get("Chinese")) //50
for (i in map){
println(i) //Chinese=50 Math=25
}
闭包
需要使用Closure
类,但是不用导入(import)
// 没有参数的闭包
def co1 = {
print("hello ")
}
def co2 = {
println("world")
}
def testCo(Closure closure1,Closure closure2){
closure1();
closure2();
}
testCo(co1,co2) // hello world
// 有参数的闭包
def closure = {
String v-> // 参数类型可以不指定,直接写个 v
println(v.length())
for(i in v){
print(i+",")
}
}
static def testCo(Closure closure){
closure('hello');
}
testCo(closure)
// 5
// h,e,l,l,o,
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 chl'blog!