Xelian
Xelian

Reputation: 17198

Dynamic method invocation in Groovy

I want to call method1 or method2 on method based on parameter code is it null or not

void add(def code, def index) {
    method(index).((code != null) ? "method1"(code) : "method2"())
}

But nothing happens? Where is my wrong? If I write

method(index)."method1"(code)

works but can not make the ternary operator works.

Upvotes: 4

Views: 335

Answers (1)

tim_yates
tim_yates

Reputation: 171054

You could do:

void add(def code, def index) {
    method(index).with { m ->
        (code != null) ? m."method1"(code) : m."method2"()
    }
}

Or (as @IgorArtamonov points out in the comments above):

void add(def code, def index) {
    (code != null) ? method(index)."method1"(code) : method(index)."method2"()
}

Upvotes: 5

Related Questions