Groovy 學習筆記 一

2021-05-09 07:34:27 字數 2794 閱讀 4411

1.

關於字串:

簡單字串可以用單引號和雙引號

, 但如果使用

gstring,

則必須使用雙引號

. 比如

「$foo, hello world

」多行字串則可以使用

「」" (3

個雙引號

), 例如:

def text = 「」"/

hello there $

how are you today?「」"

如果對這個

text

進行輸出

,會發現輸出是按原樣式輸出的

,即換行符也輸出

. 這在處理類似

html

**時時特別有用的.

另外,

可以使用/…

/ 來定義字串, 如

: def basename = /[strings and gstring^//]+$/

在這種情況下

, 只需對

/ 進行轉義

: //;

但如下定義是不合法的

:def x = //,

可以這麼寫

: def x = /${}/ 2.

字串操作:

a).

字串加減操作

def string = 『hippopotamus』

print string –『

hippo』–

『mus』+

『to』==

『potato

』//

果然強悍

!!!

b).字串轉化為字元陣列『

assert string.tolist().unique().sort().join() == 『 adelnpy』

c).字串反轉

assert』string』.reverse() == 『gnirts』

def string = 『yoda said, 「can you see this?」『

def revwords= string.split(』 『).tolist().reverse().join(』 『)

assert revwords== 『this?」 see you 「can said, yoda』

d).字串查詢

def words = ['bob', 'alpha', 'rotator', 'omega', 'reviver']

def bigpalindromes = words.findall

assert bigpalindromes == ['rotator', 'reviver']

3. 數字

a).

一切皆為物件

, 數字也不例外

b).

對於非整型數字

, 使用

bigdecimal

作為預設型別

4. 日期

可以直接對日期操作

: def date = new date() + 1

還可以:

use(timecategory)

其中timecategory

是org.codehaus.groovy.runtime.timecategory

5. 方法呼叫

: 方法呼叫時

, 括號是可選的

. 例如

: print

『hello, world』

6. 方法返回值

: 預設最後一句就是方法的返回值

, 也就是說

, 最後一句的

return

語句是可有可無的

. 當然

, 如果在方法中間需要

return值,

還是要寫

return

語句才行.

7. 閉包(closure):

閉包可以訪問與閉包定義在同一

scope

的變數. 例如:

def name = 「」 //initialize variable

def printname = //define method

name = 「youssef」 //set string youssef in variable name

printname() //result: the string in the name variable is youssef

如果不在同一

scope,

那麼需要給閉包指明引數

, 引數與閉包的

body

部分用->

符號分隔

. 如果只有乙個引數

, 則該引數可不必明確寫出來

, 預設用

it 作為該引數的名稱.

def name = 「」 //initialize variable

def printname = //define method

name = 「youssef」 //set string youssef in variable name

printname(name) //result: the string in the name variable is youssef

8. 異常處理

: 不是強制性的

9. methodmissing

與propertymissing 方法:

10. categories:

class stringcategory }

use (stringcategory)

Groovy學習筆記 一 基本語法

1.變數的定義和賦值 def param type param param1,param2,param3 1,2,3 注 句尾分號可有可無 2.包的匯入 import com.a.b 解決命名衝突使用as關鍵字 import com.a.b.c as ac import com.b.b.c as b...

Groovy閉包筆記

1.最後一行將會作為返回值 2.對於map型別,機引數列表中所有的map實參並組成map傳遞給第乙個形參。3.閉包可以設定預設值 4.it可以在有且僅有乙個未顯示宣告的引數時使用 5.閉包呼叫的標準寫法是 closurename.call 6.def定義的變數對 binding.variables....

Groovy學習系列 對映

對映 雜湊 是一種引用物件的無序集合。1 對映宣告 def m 空對映 def m id 1 name tom def m 4 2 6 2,3 2 訪問對映 def info id 1 name tom info id 返回1 info value 返回null 3 對映方法 函式名稱 說明 示例 ...