Variables scope

Hi, could you please help me with a small problem. I thought that all variables (unless specified otherwise) are defined as global in groovy. However, when i run a code like shown below on Hubitat, I get null in logs. And whatever I tried, all variables seems to be local for the method they are declared in. Am I doing something wrong? Thank you.

   testVar = 1

    def initialize() {
        log.info "testVar value: ${testVar}"
        subscribeNow()
    }

It is script scope but not persistent

You should avoid script level variables due to the non persistence. They are no better than local and in many cases worse.

You can use @Field for global but these have side effect across multiple instances that are non intuitive. Also the persistence may not be what you actually want and result in holding memory that should be released.

1 Like

Well, in this particular case holding results in memory is exactly what I want. Ideally I want to persist the result to be able to use it after the instance is reinitialized. And it should be done in scope of instance. Is there a way to achieve that? And what side effects should I expect in case of @field?

See

If you need to use it across reboots you get forced into state / atomicState

1 Like

That helped a lot. Thank you!!!