Last week somebody tossed up a question of using variable number of arguments with Groovy. We’re implementing a method called ‘add‘ in the String class using meta-programming. The add method should just append any number of string arguments passed to it.
Given below is the simple code that takes in variable number of arguments.
String.metaClass.add = {String... args -> args.inject(delegate) {result,item->"${result}${item}"} } println "java".add(" is"," old") println "Groovy ".add(" is ","agile ","and ","cool")
The add method uses the ellipsis mechanism of passing variable number of arguments. The ‘args’ argument is a list that uses the inject method to append the string values passed it.