Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 777
Xelian Avatar asked Oct 14 '25 20:10

Xelian


1 Answers

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"()
}
like image 147
tim_yates Avatar answered Oct 18 '25 09:10

tim_yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!