Groovy 1.5.x / Grails 1.0.x If-Elseステートメントのバグ
-
05-07-2019 - |
質問
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
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: []
何かが足りないのですか、それともバグですか?
編集:このように変更しました:
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
}
これで動作します!グルーヴィーなif-elseコンストラクトは値を返しませんか?
解決
これは、Groovy 1.6.xで修正されたバグ/欠落機能であるため、Grails 1.1+で動作します。 Grails 1.0.x / Groovy 1.5.xの場合、各ifブランチから明示的に値を返す必要があります。
所属していません StackOverflow