Gradle系列三之Groovy基本語法

由于是學(xué)習(xí)Groovy基礎(chǔ)語法帘睦,開始我選擇的IDE是Intellij IDEA,大家可以選擇其它IDE族吻,但是都需要配置Groovy環(huán)境變量和Java環(huán)境變量暴心,這里就不一一贅述了。

Groovy中變量

Groovy沒有基本類型浩嫌,對于一些像int類型都會被包裝成對象類型Integer

int x = 1
println(x.class)

def y = 3.14
println(y.class)

y = 'hello groovy'
println(y.class)

打印輸出如下:

class java.lang.Integer
class java.math.BigDecimal
class java.lang.String

如果一個變量只在本類使用檐迟,可以直接用def去定義該變量;如果該變量還被其他類使用码耐,那么最好還是直接用具體的類型定義該變量追迟,而不是用def去定義。

Groovy中字符串
def name = 'name one'
def doubleName = "name double"
def tripleName = '''name triple'''
println name.class
println doubleName.class
println tripleName.class

打印輸出如下:

class java.lang.String

也就是說骚腥,在一般的情況下敦间,這三者都是可以表示字符串的,但是也有部分區(qū)別束铭,比如:

def sayHello = "Hello: ${name}" //可擴展做任意的表達(dá)式
println sayHello.class
println sayHello

打印輸出如下:

class org.codehaus.groovy.runtime.GStringImpl
Hello: name one

只有雙引號才可以做這種擴展廓块,注意這里的類型是GStringImpl,也就是GString的實現(xiàn)類契沫。
對于三引號带猴,也有其他兩者做不到的,比如懈万,按照某個規(guī)則顯示:

def tripleName = '''\
line one
line two
line three\
'''

打印輸出如下:

line one
line two
line three

對于一些字符串方法拴清,字符串填充center、padLeft钞速;比較大小str > str2贷掖;reverse()、capitalize()渴语、isNumber()苹威,這些方法在這里就不做贅述了,大家可以自行嘗試驾凶。

邏輯控制

由于這里if/else和while循環(huán)和Java程序使用相似牙甫,故這里只選switch/case和for循環(huán)來講掷酗。

  1. switch/case
def n = 1.23
def result
switch (n) {
    case 'hello':
        result = 'find hello'
        break
    case 'groovy':
        result = 'find groovy'
        break
    case [1, 2, 3, 'hello groovy']:  //列表
        result = 'find list'
        break
    case 12..30:
        result = 'find range'    //范圍
        break
    case Integer:
        result = 'find integer'
        break
    case BigDecimal:
        result = 'find bigDecimal'
        break
    default:
        result = 'find default'
        break
}
println result

打印輸出如下:

find bigDecimal
for循環(huán)
def sum = 0
for (i in 0..9) {
    sum += i
}

sum = 0
//對List的循環(huán)
for (i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) {
    sum += i
}

sum = 0
//對Map進行循環(huán)
for (i in ['合肥':1, '杭州':2, '南京':3]) {
    sum += i.value
}
println sum
閉包

閉包是Groovy的一個非常重要的特性,可以說它是DSL的基礎(chǔ)窟哺。閉包不是Groovy的首創(chuàng)泻轰,但是它支持這一重要特性,這就使代碼靈活且轨、輕量浮声、可復(fù)用,再也不用像Java一樣動不動就要用一個類了旋奢。

def clouser = {
    println 'Hello groovy!'
}

這種寫法就是閉包泳挥,我們可以怎樣調(diào)用閉包呢?

clouser.call()
clouser()

上面這兩種寫法都可以調(diào)用閉包至朗。閉包內(nèi)還可以傳入?yún)?shù):

def clouser = {String language ->
    println "Hello $language"
}

閉包內(nèi)默認(rèn)有一個it值屉符,用于默認(rèn)參數(shù):

def clouser = {
    println "Hello ${it}"
}
clouser.call('groovy!')
clouser('groovy!')

閉包一定是有返回值的,而且默認(rèn)是花括號中的最后一行:

def clouser = {String language ->
    "Hello ${language}"
}
def word = clouser('groovy!')
println word

打印輸出如下:

Hello groovy!

接下來我們來驗證返回值是否就是花括號的最后一行:

def clouser = {String language ->
    "Hello ${language}"
    'Hello Java!'
}
def word = clouser('groovy!')
println word

打印輸出如下:

Hello Java!

輸出結(jié)果也就驗證了花括號的最后一行就是返回值锹引。

閉包的使用

求累積:

int fun(int number) {
    def result = 1
    1.upto(number, {num -> result *= num})
    return result
}
println fun(5)

還可以這樣寫:

int fun(int number) {
    def result = 1
    1.upto(number) {
        num -> result *= num
    }
    return result
}

求累加:

int fun2(int number) {
    def result = 1
    number.times {
        num -> result += num
    }
    return result
}
println fun2(5)

要注意矗钟,這里只是累加到4,也就是1+0+1+2+3+4 = 11

字符串與閉包結(jié)合使用

1.字符串的each函數(shù):

def str = 'the 2 add 3 is 5'
str.each {
    temp -> print temp
}

打印輸出如下:

the 2 add 3 is 5

2.字符串的find函數(shù):

def finder = str.find {
    it.isNumber()
}
println finder

打印輸出如下:

2

也就是說find函數(shù)式查找字符串中符合閉包條件的第一個元素嫌变,找到了就直接返回吨艇。

3.字符串的findAll函數(shù):

println str.findAll {
    it.isNumber()
}

打印輸出如下:

[2, 3, 5]

4.字符串的any函數(shù):

println str.any {
    it.isNumber()
}

打印輸出如下:

true

只要有一個元素符合閉包的條件,就返回true

5.字符串的every函數(shù):

println str.every {
    it.isNumber()
}

打印輸出如下:

false

當(dāng)所有的元素都符合閉包條件的時候初澎,才返回true

6.字符串的collect函數(shù):

println str.collect {
    it.toUpperCase()
}

打印輸出如下:

[T, H, E,  , 2,  , A, D, D,  , 3,  , I, S,  , 5]
閉包進階

閉包的三個重要變量:this秸应、owner、delegate

def scriptClouser = {
    println "scriptClouser this:" + this    //代表閉包定義處的類
    println "scriptClouser owner:" + owner  //代表閉包定義處的類或者對象
    println "scriptClouser delegate:" + delegate    //代表任意對象碑宴,默認(rèn)與owner一致
}
scriptClouser.call()

打印輸出如下:

scriptClouser this:VariableStudy@3efa6afc
scriptClouser owner:VariableStudy@3efa6afc
scriptClouser delegate:VariableStudy@3efa6afc

this、owner桑谍、delegate三者代表同一個對象VariableStudy實例對象

接下來延柠,我們初始化一個內(nèi)部類Person:

class Person {
    def classClouser = {
        println "classClouser this:" + this
        println "classClouser owner:" + owner
        println "classClouser delegate:" + delegate
    }

    def say() {
        def classClouser = {
            println "methodClouser this:" + this
            println "methodClouser owner:" + owner
            println "methodClouser delegate:" + delegate
        }
        classClouser.call()
    }
}

Person p = new Person()
p.classClouser.call()
p.say()

打印輸出如下:

classClouser this:Person@6ccead66
classClouser owner:Person@6ccead66
classClouser delegate:Person@6ccead66
methodClouser this:Person@6ccead66
methodClouser owner:Person@6ccead66
methodClouser delegate:Person@6ccead66

this、owner锣披、delegate三者還是表示同一個對象Person實例對象
現(xiàn)在我們在閉包中再定義一個閉包:

def nestClouser = {
    def innerClouser = {
        println "innerClouser this:" + this
        println "innerClouser owner:" + owner
        println "innerClouser delegate:" + delegate
    }
    innerClouser.call()
}
nestClouser.call()

打印輸出如下:

innerClouser this:VariableStudy@a072d8c
innerClouser owner:VariableStudy$_run_closure9@44d88759
innerClouser delegate:VariableStudy$_run_closure9@44d88759

這時候this表示的是類VariableStudy的實例對象贞间,而owner和delegate都表示內(nèi)部閉包中的實例化對象innerClouser。

那么如何修改delegate和owner不一樣呢雹仿?

def nestClouser = {
    def innerClouser = {
        println "innerClouser this:" + this
        println "innerClouser owner:" + owner
        println "innerClouser delegate:" + delegate
    }
    innerClouser.delegate = p //修改默認(rèn)的delegate
    innerClouser.call()
}
nestClouser.call()

打印輸出如下:

innerClouser this:VariableStudy@55dee8d0
innerClouser owner:VariableStudy$_run_closure9@239494f6
innerClouser delegate:Person@52765b39

總結(jié):
1.在類或者方法中定義閉包增热,那么this、owner胧辽、delegate都是一樣的(默認(rèn)不改變delegate)峻仇;
2.如果在閉包中又嵌套一個閉包,那么this邑商、owner摄咆、delegate將不再一樣凡蚜,this將指向閉包定義處外層的實例變量或者類本身(最接近的);而owner和delegate都會指向最近的閉包對象吭从;
3.只有人為的修改delegate朝蜘,delegate和owner才會不一樣(this和owner不可以修改)

閉包的委托策略
class Student {
    String name
    def pretty = {
        "my name is ${name}"
    }
}

class Teacher {
    String name
}

Student stu = new Student(name: "John")
Teacher tea = new Teacher(name: "jack")
println stu.pretty.call()

打印輸出如下:

my name is John

接下來我們做如下的修改:

class Student {
    String name
    def pretty = {
        "my name is ${name}"
    }
}

class Teacher {
    String name
}

Student stu = new Student(name: "John")
Teacher tea = new Teacher(name: "jack")
stu.pretty.delegate = tea
stu.pretty.resolveStrategy = Closure.DELEGATE_FIRST
println stu.pretty.call()

打印輸出如下:

my name is jack

以上就是閉包的委托策略。

喜歡本篇博客的簡友們涩金,就請來一波點贊谱醇,您的每一次關(guān)注,將成為我前進的動力步做,謝謝副渴!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市辆床,隨后出現(xiàn)的幾起案子佳晶,更是在濱河造成了極大的恐慌,老刑警劉巖讼载,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件轿秧,死亡現(xiàn)場離奇詭異,居然都是意外死亡咨堤,警方通過查閱死者的電腦和手機菇篡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來一喘,“玉大人驱还,你說我怎么就攤上這事⊥箍耍” “怎么了议蟆?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長萎战。 經(jīng)常有香客問我咐容,道長,這世上最難降的妖魔是什么蚂维? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任戳粒,我火速辦了婚禮,結(jié)果婚禮上虫啥,老公的妹妹穿的比我還像新娘蔚约。我一直安慰自己,他們只是感情好涂籽,可當(dāng)我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布苹祟。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪苔咪。 梳的紋絲不亂的頭發(fā)上锰悼,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天,我揣著相機與錄音团赏,去河邊找鬼箕般。 笑死,一個胖子當(dāng)著我的面吹牛舔清,可吹牛的內(nèi)容都是我干的丝里。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼体谒,長吁一口氣:“原來是場噩夢啊……” “哼杯聚!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起抒痒,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤幌绍,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后故响,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體傀广,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年彩届,在試婚紗的時候發(fā)現(xiàn)自己被綠了伪冰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡樟蠕,死狀恐怖贮聂,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情寨辩,我是刑警寧澤吓懈,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站骄瓣,受9級特大地震影響耍攘,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜畔勤,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望庆揪。 院中可真熱鬧式曲,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽则吟。三九已至,卻和暖如春敬扛,著一層夾襖步出監(jiān)牢的瞬間晰洒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留铝宵,地道東北人打掘。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓华畏,卻偏偏與公主長得像,于是被迫代替她去往敵國和親尊蚁。 傳聞我的和親對象是個殘疾皇子亡笑,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,614評論 2 353