Groovy 1.5.x/Grails 1.0.x If-Else语句错误
我在Grails 1.0.4 Groovy控制台中有以下代码:Groovy 1.5.x/Grails 1.0.x If-Else语句错误,grails,groovy,if-statement,Grails,Groovy,If Statement,我在Grails 1.0.4 Groovy控制台中有以下代码: def devices = Device.getAll() def found = devices.findAll { if(it?.localNumber && it?.areaCode){ def pattern = ~".*${it.areaCode + it.localNumber}" def matches = "$msisdn" ==~ pattern
def devices = Device.getAll()
def found = devices.findAll {
if(it?.localNumber && it?.areaCode){
def pattern = ~".*${it.areaCode + it.localNumber}"
def matches = "$msisdn" ==~ pattern
println "$matches == msisdn: $msisdn ==~ pattern: $pattern"
matches
} else {
false
} // if-else
}
println "found: $found"
其中返回以下内容:
discovering device: 048123456
true == msisdn: 048123456 ==~ pattern: .*48123456
true == msisdn: 048123456 ==~ pattern: .*48123456
true == msisdn: 048123456 ==~ pattern: .*48123456
false == msisdn: 048123456 ==~ pattern: .*48123457
found: []
我是遗漏了什么还是一个bug
编辑:我改成这样:
def found = devices.findAll {
def matches = false
if(it?.localNumber && it?.areaCode){
def pattern = ~".*${it.areaCode + it.localNumber}"
matches = "$msisdn" ==~ pattern
println "$matches == msisdn: $msisdn ==~ pattern: $pattern"
} else {
matches = false
} // if-else
matches
}
现在它工作了!groovy if else构造不应该返回一个值吗?这是groovy 1.6.x中修复的一个bug/缺少的特性,因此它可以在Grails 1.1+中工作。对于grails1.0.x/groovy1.5.x,需要从每个if分支显式返回一个值