「Groovy」- 控制结构 | Loop | 循环 | If | Switch | 条件 | 循环

if

println false ? 1 : 2 // 2
println false ?: 2 // 2
println true ?: 2 // true

dictionary – groovy: safely find a key in a map and return its value – Stack Overflow

def mymap = [name:"Gromit", id:1234]
def x = mymap.find{ it.key == "likes" }?.value
if(x)
    println "x value: ${x}"

println x.getClass().name

?. checks for null and does not create an exception in Groovy. If the key does not exist, the result will be a org.codehaus.groovy.runtime.NullObject.

Switch

// 将 Gitee 的团队名转化到对应的 k8s 的命名空间
// 因为团队名不符合规范,所以加个转换层,映射到 k8s 命名空间
def giteeTeamToK8sNamespace(String giteeTeamName) {
    def returnVal = 'default'

    switch (giteeTeamName) {
    case 'KaiFa':
            returnVal = 'df-common'
            break
    case 'YunWei':
            returnVal = 'df-om'
            break
    }

    return returnVal
}

循环 | Loop

使用 each 方法

listFoo.each { item ->
	// do some stuff
}

使用 find 方法

Can you break from a Groovy “each” closure?

当使用 find 遍历时,在 Cloure 中返回 true 将停止遍历:

def a = [1, 2, 3, 4, 5, 6, 7]

a.find {
    if (it > 5)
    	return true // break
    println it  // do the stuff that you wanted to before break
    return false // keep looping
}

// 该程序将输出 1, 2, 3, 4, 5

也可以通过元编程实现自己的 find 函数:

List.metaClass.eachUntilGreaterThanFive = { closure ->
    for ( value in delegate ) {
        if ( value  > 5 ) break
        closure(value)
    }
}

def a = [1, 2, 3, 4, 5, 6, 7]

a.eachUntilGreaterThanFive {
    println it
}