Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a map from existing variables (e.g. a Java equivalent to JavaScript's `{varA, varB, varC}`)

Tags:

java

groovy

I'm primarily a JavaScript developer, but am currently working on some Groovy code and haven't been able to figure out how to do something that's super-simple in JavaScript.

The JavaScript equivalent of what I'm trying to do follows.

I'm specifically trying to figure out the Java (or Groovy) equivalent of creating an object in JS (map in Java) out of just the existing variable names, e.g. {a, b, c} shorthand in the code snippet below. Any guidance will be much appreciated!

javaScriptExample()

function javaScriptExample () {
  // the variables already exist in the program that I'm working in
  const a = 'a'
  const b = 'bee'
  const c = 'see'
  
  //                ➡️ Here's where I'm stuck. ⬅️  
  // I simply want to be able to arbitrarily pass variable keys and values
  // as a map to another function, _using just the variable keys_,
  // e.g. the equivalent of JavaScript's `{a, b, c}` in the next call
  doOtherStuffWithVariables({a, b, c})
}

function doOtherStuffWithVariables (obj) {
  for (const key in obj) {
    console.log(`variable ${key} has a value of "${obj[key]}" and string length of ${obj[key].length}`)
  }
}
like image 223
MetaSean Avatar asked May 01 '26 09:05

MetaSean


1 Answers

As stated, there is no shortcut in Groovy. But if you want/need this syntax, you can achieve this with Groovy Macros.

E.g. a very straight forward attempt:

@Macro
static Expression map(MacroContext ctx, final Expression... exps) {
    return new MapExpression(
        exps.collect{
            new MapEntryExpression(GeneralUtils.constX(it.getText()), it)
        }
    )
}

Usage:

def a = 42
def b = 666

println(map(a,b))
// → [a:42, b:666]
like image 160
cfrick Avatar answered May 03 '26 23:05

cfrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!