soapergem
soapergem

Reputation: 10029

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.

Upvotes: 1

Views: 62

Answers (1)

chubbsondubs
chubbsondubs

Reputation: 38885

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
    }
}

Upvotes: 4

Related Questions