Groovy入门

参考精通 Groovy

//groovy start
def range = 0..4
println "range's class : \t" + range.class
assert range instanceof List

def numbers = [1, 2, 3, 4]
println "numbers's class : \t" + numbers.class
assert numbers + 5 == [1, 2, 3, 4, 5]
assert numbers - [2, 3] == [1, 4]

def coll = ["Groovy", "Java", "Ruby"]
assert coll instanceof Collection
assert coll instanceof ArrayList
coll.add("Python")
coll << "Smalltalk"
coll[5] = "Perl"
println "coll is : \t" + coll

def hash = [name: "Andy", "VPN-#": 45]
assert hash.getClass() == LinkedHashMap
hash.put("id", 23)
assert hash.get("name") == "Andy"
hash.dob = "01/29/76"
assert hash.dob == "01/29/76"
assert hash["name"] == "Andy"
hash["gender"] = "male"
assert hash.gender == "male"
assert hash["gender"] == "male"

//闭包
coll.each {
    println it
}
println "-----------------------"
hash.each { x ->
    println x
}
println "-----------------------"
hash.each { k, v ->
//    ${}替代+ 连接字符串
    println "${k}\t${v}"
}
println "-----------------------"
"ITERATION".each {
    print it.toLowerCase()
}
println()

def excite = { word ->
    return "${word}!!"
}
assert "Groovy!!" == excite("Groovy")
assert "Java!!" == excite.call("Java")
println "-----------------------"

//class
//def song = new Song(name: "Le Freak", artist: "Chic", genre: "Disco")
def song = new Song()
song.name = "Funkytown"
song.artist = "Lipps Inc."
song.setGenre("Disco")
assert song.getArtist() == "Lipps Inc."

song.setGenre "Jazz"
assert song.genre == "Jazz"
println song

def sng2 = new Song(name:"Thriller", artist:"Michael Jackson")
println sng2
//NPE
//println sng2.genre.toUpperCase
println sng2.genre?.toUpperCase

class Song {
    def name
    def artist
    def genre

    @Override
    String toString() {
        "${name} ${artist} ${genre}"
    }
}

本文链接:

https://blog.wfyvv.com/archives/41.html
1 + 1 =
快来做第一个评论的人吧~