Pass method as parameter in Groovy

依然范特西╮ 提交于 2019-12-03 08:11:01

问题


Is there a way to pass a method as a parameter in Groovy without wrapping it in a closure? It seems to work with functions, but not methods. For instance, given the following:

def foo(Closure c) {
    c(arg1: "baz", arg2:"qux")
}

def bar(Map args) {
    println('arg1: ' + args['arg1'])
    println('arg2: ' + args['arg2'])
}

This works:

foo(bar)

But if bar is a method in a class:

class Quux { 
    def foo(Closure c) {
        c(arg1: "baz", arg2:"qux")
    }

    def bar(Map args) {
        println('arg1: ' + args['arg1'])
        println('arg2: ' + args['arg2'])
    }

    def quuux() { 
      foo(bar)
    }
} 

new Quux().quuux()

It fails with No such property: bar for class: Quux.

If I change the method to wrap bar in a closure, it works, but seems unnecessarily verbose:

    def quuux() { 
      foo({ args -> bar(args) })
    }

Is there a cleaner way?


回答1:


.& operator to the rescue!

class Quux { 
    def foo(Closure c) {
        c(arg1: "baz", arg2:"qux")
    }

    def bar(Map args) {
        println('arg1: ' + args['arg1'])
        println('arg2: ' + args['arg2'])
    }

    def quuux() { 
      foo(this.&bar)
    }
} 

new Quux().quuux()
// arg1: baz
// arg2: qux

In general, obj.&method will return a bound method, i.e. a closure that calls method on obj.



来源:https://stackoverflow.com/questions/15231810/pass-method-as-parameter-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!