Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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}`)
  }
}
question from:https://stackoverflow.com/questions/65906680/create-a-map-from-existing-variables-e-g-a-java-equivalent-to-javascripts-v

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...