Dark theme | Light theme

July 13, 2022

Groovy Goodness: Using Macros For Getting More Information About Variables

In a previous post we learned about the macros SV, SVI and SVD that return a string representation of variables with their name and value. Groovy 4 also added the NP and NPL macros that we can use to inspect variables. Instead of returning a GString instance these macros return a NamedValue instance or a list of NamedValue value instances. The NamedValue class is a simple class with a property name, containing the name of the variable, and property val with the value of the variable. The macro NP can be used when we have a single variable and result is a single NamedValue instance. An the macro NVL can be used with multiple variables. The result is a list of NamedValue instances where each instance represent a variable passed as argument to NVL.

In the following example we use NV and NVL:

def languages = ["Java", "Groovy", "Clojure"]

// Use NV macro to create a NamedValue object 
// with name and val properties containing the
// variable name and variable value.
def namedValue = NV(languages)

assert == "languages"
assert namedValue.val == ["Java", "Groovy", "Clojure"]
assert == "groovy.lang.NamedValue"

def alias = "mrhaki"
def name = "Hubert"
def age = 49

// We can pass multiple objects with the NVL macro
// and we get a List with multiple NamedValue objects.
def namedValues = NVL(alias, name, age)
assert namedValues.size() == 3
assert namedValues == [new NamedValue("alias", "mrhaki"), new NamedValue("name", "Hubert"), new NamedValue("age", 49)]

// We can use Groovy collection methods.
assert namedValues[0].name == "alias"
assert namedValues[0].val == "mrhaki"
assert == ["alias", "name", "age"]
assert namedValues.val == ["mrhaki", "Hubert", 49]
assert namedValues.find { nv -> == "age" }.val == 49

Written with Groovy 4.0.3.