Groovy Switch Statement

Just playing around here, but trying to implement a Switch statement using a text variable. Here is my code. It doesn't work and wondering if it is possible and how to do it.

def initialize() {
subscribe(location, "variable:varName", nameHandler)
}

def nameHandler(evt) {
log.debug "${evt.value}"

switch (evt.value) {
    case "Name1": log.debug "Name is Name1";
    case "Name2": log.debug "Name is Name2";

}

}

The best first step would be figuring out what exactly doesn’t work. Putting some log statements through throughout your code to see what is or isn’t running would be the biggest help for that. For example, you could put one at the beginning of your handler method to see if it’s running--And maybe also print the value of evt.value to see if it’s what you expect.

1 Like

Just spitballing here, but suggest casting toString and make sure you have breaks; and strange to have the case 'uppercase' in the evt.value, so add a default to tell you what you missed.

String name = evt.value.toString()
switch (name) {
    case "Name1": log.debug "Name is $name"; break
    case "Name2": log.debug "Name is $name"; break
   default:
        log.debug "${device.displayName} did not process name:$name
}
2 Likes

There is a log statement at beginning of handler that prints out the value and that is working.

That worked. I just assumed since the variable was a string I wouldn't have to do that, but.....

2 Likes