简体   繁体   English

我可以在Groovy中代替闭包吗?

[英]Can I pass in a method in place of a closure in Groovy?

Let's say I've got something like this: 假设我有这样的事情:

class Test {

    def test_method() {
        def http = new HTTPBuilder("http://rest.request.com")
        http.request(groovyx.net.http.Method.GET) { req ->
            uri.path = "/path/to/rest/request"
            response.success = {resp, reader ->
                println resp
            }
        }
    }

}

This works fine and all, but I'd really prefer to do something like this: 一切正常,但是我真的更喜欢做这样的事情:

class Test {

    def print_resp(String resp) {
        println resp
    }

    def test_method() {
        def http = new HTTPBuilder("http://rest.request.com")
        http.request(groovyx.net.http.Method.GET) { req ->
            uri.path = "/path/to/rest/request"
            response.success = print_resp
        }
    }

}

Except I've got the syntax wrong there. 除非我的语法错误。 Please help me understand what I'm doing wrong. 请帮助我了解我在做什么错。

You want to use the .& syntax: 您要使用。&语法:

def test_method() {
    def http = new HTTPBuilder("http://rest.request.com")
    http.request(groovyx.net.http.Method.GET) { req ->
        uri.path = "/path/to/rest/request"
        response.success = this.&print_resp
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM