Return multiple items from a method via a class or struct

smartapp

(baboucarr) #1

Hi,
I am trying to create a methods, that returns to distinct set of values, device and device type. here is the method

def findDevice(device) {
log.debug "trying to find device - $device"
def foundDevice

// first search in switches
log.debug "finding id - ${device.id}"
def switchDevice = switches.find{it.id == device.id}
if (switchDevice) {
	log.debug "Found ${switchDevice.displayName} in switches"
    // group the type, and device to return back
    foundDevice.type = "switch"
    foundDevice.device = switchDevice
}

// look for device in thermostat
def thermDevice = thermostats.find(it.id == device.id)
if (thermDevice) {
	log.debug "Found ${thermDevice.displayName} in thermostats"
    // group the type, and device to return back
    foundDevice.type = "thermostat"
    foundDevice.device = thermDevice  
}

return foundDevice

}

I create a def for foundDevice and added type. and device as properties of it so that I can later access them. I know that classes are not supported in ST. But is something this straight forward supported one way or another. The code compiles but I get a runtime error when setting the type resulting nullPointerExpection for the foundDevice.

Does ST or groovy allow me to return different items if I cannot create my own class or struct.

thanks


(Jim Anderson) #3

Lists and Maps work well for this scenario:

// a list
def foundDevices = []

// first search in switches
log.debug "finding id - ${device.id}"
def switchDevice = switches.find{it.id == device.id}
if (switchDevice) {
log.debug "Found ${switchDevice.displayName} in switches"
    // add the device info as a map to the list
    foundDevices << [type: "switch", device: switchDevice]
}

// look for device in thermostat
def thermDevice = thermostats.find(it.id == device.id)
if (thermDevice) {
    log.debug "Found ${thermDevice.displayName} in thermostats"
    // add the device info as a map to the list
    foundDevices << [type: "thermostat", device: thermDevice]
}

return foundDevices

That will return a list of maps like this: [ [type: "switch", device: someDeviceObject], [type: "thermostat", device: someThermObject] ].

You can then get at and work with the data in a number of ways:

// list all found devices and their type
foundDevices.each { log.debug "type: $it.type, device: $it.device"}

(baboucarr) #4

Great, Thanks Jim, yes that does solve it for my case. :+1: