美文网首页
groovy closure初次使用

groovy closure初次使用

作者: 来福马斯特 | 来源:发表于2017-09-19 21:31 被阅读18次

    groovy closure初次使用

    closure是groovy里比较有特色的一个东西,有点类似与java8里的lambda表达式,但是比lambda有着
    更加灵活的应用
    语法上的差异
    java8 lambda

    (int number)->{System.out.println(number);}
    //or
    number -> System.out.prinltn()
    

    groovy clouser

    {int number -> println(number)}
    //or
    {number -> println(number)}
    //or
    {println(it)}
    

    注意的主要是这个大括号的位置
    再来个scala的function literal

    (a:Int)=>{println(a)}
    //or
    a => println(a)
    

    groovy 里,如果像

    {println(it)
    

    这样,省略掉参数部分,closure还是有一个默认参数it的,如果真想定义一个
    无参的clouser,必须这样

    {()->println("No args")}
    

    closure作为普通参数,变量,或者返回值

    def printer = { line -> println line }
    

    定义一个closure并且赋值给变量printer,此时,printer的类型就是Closure

    def Closure getPrinter() {
    return { line -> println line }
    }
    

    返回一个Closure

    将普通方法用作Closure

    class WithFilter { //default public
        Integer limit  //default public
        boolean sizeUpTo(String value) {
            return value.size() <= limit
        }
    }
    WithFilter width10Filter = new WithFilter(limit:10)
    WithFilter width5Filter = new WithFilter(limit:5)
    
    Closure sizeUpTo6 = width10Filter.&sizeUpTo //store to a variable
    def words = ['long string', 'medium', 'short', 'tiny']
    
    assert 'medium' == words.find (sizeUpTo6)
    assert 'short' == words.find (width5Filter.&sizeUpTo)
    

    巩固例子

    //direct call through method
    Map map = ['a':1,'b':2] //groovy define a map 
    map.each{key,value -> map[key] = value +1 }
    assert map == ['a':2,'b':3]
    
    //assign to a variable
    def doubler = {key,value -> map[key] = value + 1}
    map.each(doubler)
    assert map == ['a':2,'b':3]
    
    //get closure from a method 
    def doubleMethod(entry){
        entry.value = entry.value + 1
    }
    
    doubler = this.&doubleMethod
    map.each(doubler)
    assert map == ['a':2,'b':3]
    

    以上就是groovy最简单的closure入门,后续的delegation等高级知识,有空我再学习补充下。

    眼下,groovy最重要的使用也就是gradle编译工具。感觉groovy的发展确实不如scala来的火热。

    相关文章

      网友评论

          本文标题:groovy closure初次使用

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