天天看點

Groovy基本句法

Gradle作為一個建構工具自然不會自己去創造一門語言來支撐自己,那麼它用的是哪門子語言呢?什麼語言能寫成這樣:

task hello {
    doLast {
        println 'Hello world!'
    }
}      

如此風騷的文法自然要歸Groovy莫屬了。

什麼是Groovy

官方介紹如下:

Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.

大概意思是Groovy是一門運作在java平台上的強大的、可選類型的、動态語言。使用Groovy可以使你的應用具備腳本,DSL定義,運作時和編譯時元程式設計,函數式程式設計等功能。

接下來将分幾個小節簡單介紹Groovy的文法規範。

Groovy文法

注釋

Groovy使用的注釋有一下幾種:

1.單行注釋

// a standalone single line commentprintln "hello" // a comment till the end of the line      

2.多行注釋

/* a standalone multiline comment
   spanning two lines */println "hello" /* a multiline comment starting
                   at the end of a statement */println 1 /* one */ + 2 /* two */      

3.文檔注釋

/**
 * A Class description
 */class Person {
    /** the name of the person */
    String name    /**
     * Creates a greeting method for a certain person.
     *
     * @param otherPerson the person to greet
     * @return a greeting message
     */
    String greet(String otherPerson) {       "Hello ${otherPerson}"
    }
}      

4.組織行

#!/usr/bin/env groovyprintln "Hello from the shebang line"      

這類腳本注釋主要用于表明腳本的路徑。

字元串

單引号字元串

單引号字元串對應java中的String,不支援插入。

'a single quoted string'      

字元串連接配接

assert 'ab' == 'a' + 'b'      

三引号字元串

'''a triple single quoted string'''      

三引号字元串同樣對應java中的String,不支援動态插入。三引号字元串支援多行:

def aMultilineString = '''line one
line two
line three'''      

轉義

Groovy中使用

\

來進行轉義

'an escaped single quote: \' needs a backslash'      

雙引号字元串

"a double quoted string"      

如果雙引号字元串中沒有插入表達式的話對應的是java中的String對象,如果有則對應Groovy中的GString對象。

${}

來表示插入表達式,

$

來表示引用表達:

def name = 'Guillaume' // a plain stringdef greeting = "Hello ${name}"assert greeting.toString() == 'Hello Guillaume'      
def person = [name: 'Guillaume', age: 36]assert "$person.name is $person.age years old" == 'Guillaume is 36 years old'      
shouldFail(MissingPropertyException) {
    println "$number.toString()"}      

插入閉包表達式

def sParameterLessClosure = "1 + 2 == ${-> 3}" assert sParameterLessClosure == '1 + 2 == 3'def sOneParamClosure = "1 + 2 == ${ w -> w << 3}" assert sOneParamClosure == '1 + 2 == 3'      
def number = 1 def eagerGString = "value == ${number}"def lazyGString = "value == ${ -> number }"assert eagerGString == "value == 1" assert lazyGString ==  "value == 1" number = 2 assert eagerGString == "value == 1" assert lazyGString ==  "value == 2"      

關于閉包,暫時先看看就行,等後面具體學習完閉包以後再回來看這幾個表達式就簡單了。

三雙引号字元串

def name = 'Groovy'def template = """
    Dear Mr ${name},

    You're the winner of the lottery!

    Yours sincerly,

    Dave
"""assert template.toString().contains('Groovy')      

斜杠字元串

Groovy也可以使用

/

來定義字元串,主要用于正規表達式

def fooPattern = /.*foo.*/assert fooPattern == '.*foo.*'      
def escapeSlash = /The character \/ is a forward slash/assert escapeSlash == 'The character / is a forward slash'      
def multilineSlashy = /one
    two
    three/assert multilineSlashy.contains('\n')      
def color = 'blue'def interpolatedSlashy = /a ${color} car/assert interpolatedSlashy == 'a blue car'      

/和//和/字元串

def name = "Guillaume"def date = "April, 1st"def dollarSlashy = $/
    Hello $name,
    today we're ${date}.

    $ dollar sign
    $$ escaped dollar sign
    \ backslash
    / forward slash
    $/ escaped forward slash
    $/$ escaped dollar slashy string delimiter
/$assert [    'Guillaume',    'April, 1st',    '$ dollar sign',    '$ escaped dollar sign',    '\\ backslash',    '/ forward slash',        '$/ escaped forward slash',        '/$ escaped dollar slashy string delimiter'

        ].each { dollarSlashy.contains(it) }      

字元

單引号字元串如果隻有一個字元會被轉化成

char

類型。

清單

Groovy中清單使用

[]

表示,其中可以包含任意類型的元素:

def heterogeneous = [1, "a", true]      

使用下标進行取值和指派

def letters = ['a', 'b', 'c', 'd']assert letters[0] == 'a'     assert letters[1] == 'b'assert letters[-1] == 'd'    assert letters[-2] == 'c'letters[2] = 'C'             assert letters[2] == 'C'letters << 'e'               assert letters[ 4] == 'e'assert letters[-1] == 'e'assert letters[1, 3] == ['b', 'd']         
assert letters[2..4] == ['C', 'd', 'e']      

數組

String[] arrStr = ['Ananas', 'Banana', 'Kiwi']  

assert arrStr instanceof String[]    
assert !(arrStr instanceof List)def numArr = [1, 2, 3] as int[]      

assert numArr instanceof int[]       
assert numArr.size() == 3      

鍵值數組

def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']   

assert colors['red'] == '#FF0000'    assert colors.green  == '#00FF00'    colors['pink'] = '#FF00FF'           colors.yellow  = '#FFFF00'           assert colors.pink == '#FF00FF'assert colors['yellow'] == '#FFFF00'assert colors instanceof java.util.LinkedHashMap      
SA

繼續閱讀