views:

241

answers:

1

I have this code in a Grails 1.0.4 Groovy console:

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"

Which returns this:

discovering device: 048123456
true == msisdn: 048123456 ==~ pattern: .*48123456
true == msisdn: 048123456 ==~ pattern: .*48123456
true == msisdn: 048123456 ==~ pattern: .*48123456
false == msisdn: 048123456 ==~ pattern: .*48123457
found: []

Am I missing something or is it a bug ?

EDIT: I changed it like this:

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
}

and now it works! Shouln't the groovy if-else construct return a value ?

+2  A: 

That's a bug/missing feature that was fixed in Groovy 1.6.x, so it'll work in Grails 1.1+. For Grails 1.0.x/Groovy 1.5.x you need to explicitly return a value from each if branch.

Burt Beckwith