In Groovy we can invoke a method with a name assigned to a variable. We use the GString notation to invoke the method with the variable name. We can pass parameters to the method just like when we use the method name directly.
def s = "Groovy is so much fun"
def methods = ['Upper', 'Lower']
def result = methods.collect { s."to${it}Case"() }
assert 'GROOVY IS SO MUCH FUN' == result[0]
assert 'groovy is so much fun' == result[1]
// We can pass parameters just like a normal method invocation.
def method = 'count'
def param = 'o'
assert 3 == s."$method"(param) // s.count('o').
2 comments:
I think that .collect is a better choice than .inject in this case:
def result = methods.collect{ method -> s."to${method}Case"() }
@Joe: yes you're right. That makes for better readable (shorter) code. I changed the sample code in the post and used collect this time.
Post a Comment