昨天我們寫了一個HelloWorld,其實很簡單的.呵呵.
現在我們打開Groovy控制臺輸入:
123+45*67
按Ctrl+R,結果就會輸出來了.
Result: 3138
現在我們來看看給變更賦值
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在你需要用時才給變量賦予類型和值.
這在Java里是不可想象的.
List和Maps:
我們來看看如何來聲明一個集合:
myList = [1776, -1, 33, 99, 0, 928734928763]
和Java一樣,集合的索引是從0開始的.你可以這樣訪問:
println myList[0]

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

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

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


{
println("Good morning")

} else
{
println("Good evening")
}

這是一個簡單的判斷是上午還是下午的小程序,對于第一行你可以參考Groovy-doc.
Bool表達式:
myBooleanVariable = true
當然還有一些復雜的bool表達式:
* ==
* !=
* >
* >=
* <
* <=

來看看一些例子吧:
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表達式對于if來說是非常有用的:
if (titanicBoxOffice + trueLiesBoxOffice > returnOfTheKingBoxOffice + theTwoTowersBoxOffice)


{
println(titanicDirector + " is a better director than " + returnOfTheKingDirector)
}
再看關于天氣的例子:
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,今天到此為止吧.