闭包

作者: 龙剑灵 | 来源:发表于2020-03-16 00:26 被阅读0次
    def clouser = { name -> println "hell ${name}" }
    clouser.call() //hell null
    clouser.call("groovy") //hell groovy
    clouser("groovy") //hell groovy
    
    
    def clouser2 = { String name, int age -> println "hell ${name}, age is ${age}" }
    clouser2.call("cjt", 28) //hell cjt, age is 28
    clouser2("cjt", 28) //hell cjt, age is 28
    
    //默认参数it
    def cjt = { println "hell ${it}" }
    cjt("吉米")
    
    //求阶乘
    int fab(int number) {
        int result = 1;
        1.upto(number, { num -> result *= num })
        //1.upto(number) { num -> result *= num }
        return result
    }
    
    println fab(5)
    
    int fab2(int number) {
        int result = 1;
        number.downto(1) { num -> result *= num }
        return result
    }
    println fab2(5)
    
    int cal(int number) {
        int result = 0;
        number.times { num -> result += num }
        return result
    }
    println cal(101)
    
    10.times {
        print it + "  " //输出0 - 9
    }
    

    相关文章

      网友评论

          本文标题:闭包

          本文链接:https://www.haomeiwen.com/subject/ewxbdhtx.html