Dynamic Method Call in Groovy

I want to call method1 or method2 by method based on parametric 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 mistake? If I write

method(index)."method1"(code)

      

works, but can't get the ternary operator to work.

+3


source to share


1 answer


You can 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"()
}

      

+4


source







All Articles