昨天我們寫(xiě)了一個(gè)HelloWorld,其實(shí)很簡(jiǎn)單的.呵呵.
現(xiàn)在我們打開(kāi)Groovy控制臺(tái)輸入:
123+45*67
按Ctrl+R,結(jié)果就會(huì)輸出來(lái)了.
Result: 3138
現(xiàn)在我們來(lái)看看給變更賦值
x = 1
println x

x = new java.util.Date()
println x

x = -3.1499392
println x

x = false
println x

x = "Hi"
println x

Groovy在你需要用時(shí)才給變量賦予類型和值.
這在Java里是不可想象的.
List和Maps:
我們來(lái)看看如何來(lái)聲明一個(gè)集合:
myList = [1776, -1, 33, 99, 0, 928734928763]
和Java一樣,集合的索引是從0開(kāi)始的.你可以這樣訪問(wèn):
println myList[0]

將會(huì)輸出:
1776
你能得到集合的長(zhǎng)度
println myList.size()

將會(huì)輸出:
6
來(lái)看看Map怎樣聲明:
scores = [ "Brett":100, "Pete":"Did not finish", "Andrew":86.87934 ]
注意每個(gè)鍵的值類型都是不同的.
現(xiàn)在我們?cè)L問(wèn)一下鍵為"Pete"的值,有兩種方式:
println scores["Pete"]
println scores.Pete
會(huì)輸出:
Did not finish
Did not finish
我們也能給scores["Pete"]賦予新值
scores["Pete"] = 3
再次訪問(wèn)scores["Pete"]
println scores["Pete"]
將會(huì)輸出3
你也可以創(chuàng)建一個(gè)空集合和空Map:
emptyMap = [:]
emptyList = []

為了確保集合或Map是空的,你可以輸出一個(gè)它們的大小:
println emptyMap.size()
println emptyList.size()
輸出是0
現(xiàn)在我們來(lái)看看條件執(zhí)行吧:
amPM = Calendar.getInstance().get(Calendar.AM_PM)
if (amPM == Calendar.AM)


{
println("Good morning")

} else
{
println("Good evening")
}

這是一個(gè)簡(jiǎn)單的判斷是上午還是下午的小程序,對(duì)于第一行你可以參考Groovy-doc.
Bool表達(dá)式:
myBooleanVariable = true
當(dāng)然還有一些復(fù)雜的bool表達(dá)式:
* ==
* !=
* >
* >=
* <
* <=

來(lái)看看一些例子吧:
titanicBoxOffice = 1234600000
titanicDirector = "James Cameron"

trueLiesBoxOffice = 219000000
trueLiesDirector = "James Cameron"

returnOfTheKingBoxOffice = 752200000
returnOfTheKingDirector = "Peter Jackson"

theTwoTowersBoxOffice = 581200000
theTwoTowersDirector = "PeterJackson"

titanicBoxOffice > returnOfTheKingBoxOffice // evaluates to true
titanicBoxOffice >= returnOfTheKingBoxOffice // evaluates to true
titanicBoxOffice >= titanicBoxOffice // evaulates to true
titanicBoxOffice > titanicBoxOffice // evaulates to false
titanicBoxOffice + trueLiesBoxOffice < returnOfTheKingBoxOffice + theTwoTowersBoxOffice // evaluates to false

titanicDirector > returnOfTheKingDirector // evaluates to false, because "J" is before "P"
titanicDirector < returnOfTheKingDirector // evaluates to true
titanicDirector >= "James Cameron" // evaluates to true
titanicDirector == "James Cameron" // evaluates to true

bool表達(dá)式對(duì)于if來(lái)說(shuō)是非常有用的:
if (titanicBoxOffice + trueLiesBoxOffice > returnOfTheKingBoxOffice + theTwoTowersBoxOffice)


{
println(titanicDirector + " is a better director than " + returnOfTheKingDirector)
}
再看關(guān)于天氣的例子:
suvMap = ["Acura MDX":"\$36,700", "Ford Explorer":"\$26,845"]
if (suvMap["Hummer H3"] != null)


{
println("A Hummer H3 will set you back "+suvMap["Hummer H3"]);
}
ok,今天到此為止吧.