I must say I didn’t fully realise that either.
VSCode editor is smart enough to realize that it won’t work in rules with command or updated triggers - and complains vaguely.
"Invalid number of arguments. The method previousState(Item) is not applicable without arguments"
OpenHAB fails with a runtime error if you do try it anyway in a rule, and that’s the source of the obscure error message seen earlier -
Rule 'testing': An error occurred during the script execution: index=0, size=0
So you CANNOT even include implicit previousState in an ‘update’ rule and test for null.
But there is a way to “cheat the system” …
// ITEMS FILE
Number testX
// SITEMAP test tool so you generate change or same commands
Switch item=testX mappings=[0="0",1="1",2="2"]
Demo rule
rule "testing previousState"
when
Item testX received update or
Item testX changed
then
if (previousState !== null) {
logInfo("updtest", "Changed from " + previousState.toString + " to " + testX.state.toString)
} else {
logInfo("updtest", "This time it is null, no change " + testX.state.toString)
}
end
By including changed in the list of triggers, we are allowed to use previousState within the rule. But - not all the triggers need to actually be changed!
This rule will also run for an update when there is no change. Of course, previousState has no value in the case of no change. But the rule can now test it to see if it is null.
There is a big pitfall here.
When the item updates without change - the rule runs once (with previousState null)
When the item updates with a change - the rule runs twice, once for each trigger. Once with previousState null (as it does not get populated by the update trigger, even though it has really changed) and once with previousState valid as the old state, set by the changed trigger.
The effect of that is that an ‘update’ run of the rule will always occur and it cannot tell on that pass if the state really changed or not.
It’s a curiosity - I can’t see any real use for the cheat though.