Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: unwrapping named map arguments in method

Tags:

groovy

I'm finding myself passing a lot of variables to my methods as named arguments as it makes things a lot clearer:

doFunction(name: 'Jack', age: 27)

now in doFunction I often find myself doing this:

doFunction(Map args) {

  if (args['name']) {
    def name = args['name'] 
    // do stuff with name 
  }
} 

Is there a language feature to unwrap the Map to its respective parameters on the fly? I couldn't find anything like that. and if there wasn't, I'm curious as to why, it seems like this is the natural Groovy approach to boilerplate. I'd like a way to immediately check and work on the parameter if it exists, is there a cleaner way to do this? am I approaching Map arguments the wrong way entirely?

like image 992
akhalid Avatar asked Oct 27 '25 14:10

akhalid


1 Answers

Since there is no destructuring like e.g. in clojure, one way to work with maps like this would be using with. Like:

void destruct(Map params) {
    params.with{
        if (name) {
            println "Hello $name"
        }
        if (age) {
            println "I am $age years old"
        }
    }
}

destruct name: "World", age: 4.54e9
// => Hello World
// => I am 4.54E+9 years old
destruct name: "Computer"
// => Hello Computer

Also on the nitpicking side: those are no named arguments (like e.g. in python). It is just a syntactic sugar for passing maps. E.g. it is short for destruct([name: 'World']) -- it will not work for a method void destruct(String name, BigDecimal age)

like image 83
cfrick Avatar answered Oct 29 '25 07:10

cfrick