Groovy maps

I’m trying to wrap my head around this bit of code in the Smart Lights example in the documentation:

In preferences:

input “action”, “enum”, title: “What do you want to do?”, options: actionOptions(), required: true, submitOnChange: true

Which calls the following two functions:

// utility method to get a map of available actions for the selected switches
def actionMap() {
def map = [on: “Turn On”, off: “Turn Off”]
if (lights.find{it.hasCommand(‘setLevel’)} != null) {
map.level = “Turn On & Set Level”
}
if (lights.find{it.hasCommand(‘setColor’)} != null) {
map.color = “Turn On & Set Color”
}
map
}

// utility method to collect the action map entries into maps for the input
def actionOptions() {
actionMap().collect{[(it.key): it.value]}
}

So I understand purpose of actionMap() – it builds a map that always has on: and off:, and it will include level: and color: if it finds lights with those respective abilities.

Questions:

  1. What does actionOptions() do? I think it just re-creates the map built in actionMap(), but if so, why not just call “options: actionMap()” in the preferences?
  2. Why is “it.key” in parentheses (but not it.value)? Maybe because its a gString?

Any guidance/help would be greatly appreciated by me and the Groovy Karma Gods.

6 in one half dozen in the other. You will hear people argue one way or the other on which one is more expensive. Probably negligible.

This is a how you would add a “complex key”. This basically just tells groovy to consider them variable references. More info here and here.

2 Likes