Groovy
如何定義一個變量:不用定義類型
println為輸出類似system.out
def b = "";def為定義 “”代表字符串String型‘’也可以代表String
就是‘’中的變量也會當成字符串麻献。這是與“”的區(qū)別
$表名變量
def a=10;
def b=“$a” 打印后會輸出10
def c='$a' 打印會輸出$a
循環(huán)
第一種
for(int i=0份企;i<3;i++){、/循環(huán)三次
println"sdsd";
}
第二種 range方式
for(i in 0..2){//循環(huán)三次
println'sdsd';
}
其它實現(xiàn)方式
0.upto(2){//從0到2 循環(huán)三次
println‘sdsd‘杯道;
}
3.times(){println "$it"}//執(zhí)行三次
0.step(10,2){println“it”}//步長 從0到10每循環(huán)一次加2
//閉包概念:像是一個方法{}是作為參數(shù)
0.upto(2,{//從0到2
println‘sdsd‘垛膝;
})
安全導航操作符?.
String a =null
prinln a?.method();
?.當a為null時會不執(zhí)行method()方法锤灿,會打印出null赘艳,避免了空指針a報錯
4.javaBean
省略了get酌毡、set方法
class Person{
String name;
}
默認public
Person p = new Person()蕾管;
p.name
5.靈活初始化與具名參數(shù)(name:"value")
Groovy 可以靈活的初始化一個JavaBean類枷踏。在構(gòu)造對象時,可以簡單地以逗號分隔得鍵值對來給出屬性值掰曾。如果類有一個無參構(gòu)造器旭蠕,該操作會在構(gòu)造器之后執(zhí)行
class Robbt {
def type,height,width
def toString2(){
println "type: $type,height:$height,width:$width"
}
}
6可選形參
Groovy中可以把方法和構(gòu)造器的形參設(shè)為可選旷坦。實際上掏熬,我們想設(shè)置多少就設(shè)置多少,但這種必須在末尾秒梅。
就是調(diào)用方法是可以不給這個參數(shù)值旗芬,因為他有默認值。
${type,height}取兩個值
閉包將代碼塊作為一個參數(shù)
//好看一些番电,Groovy規(guī)定岗屏,如果方法的最后一個參數(shù)是閉包,可以放到方法外面 numList.each(){ println it }
//正常 numList.each({ println it })
def bibao(closure){
for(i in 1..`10){
closure(i)
}
}
bibao{
println it
}
閉包中可以包含代碼邏輯漱办,閉包中最后一行語句,表示該閉包的返回值婉烟,不論該語句是否冠名return關(guān)鍵字娩井。
如果c是無參數(shù)閉包,那么它的標準調(diào)用方法是c.call(),它的簡潔調(diào)用方法是c()似袁。見代碼:
def a = 'coffee'
def c = {
def b = 'tea'
a + ' and ' + b //a refers to the variable a outside the closure,
//and is remembered by the closure
}
assert c() == 'coffee and tea' //short for c.call()
grep(xxx) 作用是過濾xxx的方法
將map轉(zhuǎn)成list RulesBpi.collect{k,v->newMagicCubeConfig.MagicCubeRule(k,v)}