代码之家  ›  专栏  ›  技术社区  ›  Azder

groovy 1.5.x/grails 1.0.x if-else语句错误

  •  2
  • Azder  · 技术社区  · 16 年前

    我在grails 1.0.4groovy控制台中有以下代码:

    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
    }
    

    现在它开始工作了!groovy if else构造是否应返回值?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Burt Beckwith    16 年前

    这是一个在groovy 1.6.x中修复的bug/missing特性,因此它将在grails 1.1+中工作。对于grails 1.0.x/groovy 1.5.x,需要显式地从每个if分支返回一个值。

    推荐文章