Unfortunately you can’t. Its a limitation of the language unfortunately. When I’ve encountered this sort of problem I’ve either found a way to not need the reference to the local variable or resorted to using a while loop, regular for loop, or Iterator.
You may be able to do it in this round-about manner:
import org.openhab.core.library.items.*
import org.openhab.core.library.types.StringType
var StringType foo = new StringType("50")
rule "test rule 2"
when
Time cron "0/5 * * * * ?"
then
var sl = GWindow.members
sl.forEach [ ts |
logInfo("test-const", " setting dimmer: " + ts.name)
ts.sendCommand(foo)
]
end
Not sure how supported that’ll be, but it does compile, and it sends the command to the target Item (in my case derived from Group, but should be similar for you)
That should work fine and I should elaborate on my original answer. You can access an outside variable in the foreach but only to read it. You can’t modify it.
An even easier approach (equally as ugly) would be to declare a hashMap or arryList using “val” with your variable in it. The container would be final so the foreach can get to it but you can still modify the stuff inside.
The best guard against Uninitialized is to use Persistence with restoreOnStartup (preferred) or a System started rule that sets your Items to a default (less preferred).
Indeed but in my experience, since I set up persistence nearly a year ago I have never seen an Undefined state in any of my rules. It is pretty rock solid in my experience, reliable enough that I have no checks for it in any of my rules.