Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

functional programming - Pass method as parameter in Groovy

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?

question from:https://stackoverflow.com/questions/15231810/pass-method-as-parameter-in-groovy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.& 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...