Switch / case doesn't work

  • Platform information:
    • Hardware: Pi4
    • openHAB version: 3.1.0

Hi, I’m in trouble with the switch/case-statement in my rule:

var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);
var ScriptExecution = Java.type("org.openhab.core.model.script.actions.ScriptExecution");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");

var xyz = itemRegistry.getItem("ZigbeeButton02_Action").getState();

logger.info("getState: X" + xyz + "X");

if (xyz == "single") { logger.info("JA, single (if)!") }

switch (xyz) {
  case "single": {
    logger.info("JA, single (case)!");
    break;
    }
  default: {
       logger.info("default!"+xyz+"!")
  }
}

events.postUpdate("ZigbeeButton02_Action", "---");

If the ZigbeeButton02_Action changed to “single”, this log ist produced:

2021-10-25 19:05:45.884 [INFO ] [org.openhab.rule.Button02_handle    ] - getState: XsingleX

2021-10-25 19:05:45.899 [INFO ] [org.openhab.rule.Button02_handle    ] - JA, single (if)!

2021-10-25 19:05:45.901 [INFO ] [org.openhab.rule.Button02_handle    ] - default!single!

but i expected “JA, single (case)!”

Any ideas? Thanks for help!

xyz isn’t the String “single”. It’s an Item’s state, in this case a StringType. I suspect that switch uses === instead of == in the comparisons. === also looks at the type, not just the value.

So you need to convert the StringType to just a plain old String.

var xyz = itemRegistry.getItem("ZigbeeButton02_Action").getState().toString();

or using the items dict

var xyz = items["ZigbeeButton02_Action"].toString();

Great, that’s it! Thanks a lot!