@Field scope of a Map?

First, the behavior of @Field-annotated variables hasn't been formally divulged to us by staff, as far as I can tell, so I'm not sure I'd recommend it for usage outside of their documented recommendations. However, it appears others, including at least nh.schottfam in this post (who I assume depends on this behavior for webCoRE and would notice if it were different), discovered it can persist between executions in the way that you describe.

I suspect the issue is indeed your initialization of the variable:

@Field String testString="Hi Kevin"

If you aren't familiar with Groovy, all top-level code in a script (which, without seeing Hubitat's exact implementation, I would assume apps and drivers count as) gets shoved inside a method (run(), to be precise), and then that method is (wait for it...) run whenever the script is run (which would be every time an app or driver is invoked on Hubitat since they don't stay constantly "running," just run when invoked somehow), so that would include your initialization code in this example. (The @Field annotation just ups their scope so they aren't restricted to just the run() method, which would not do you any good for pretty much any of your actual code.)

tl;dr can you just declare it, initialize it somewhere else if/when needed, and then use it in the way you're trying to do?

2 Likes