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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With