How to set mutable global variable in Kotlin

I’d like to make a global variable mutable, and use it in further methods, try to implement it with companion object, but not sure whether it’s thread safe, here is what I intend to do.

  companion object {
      private var flag = false

      fun modifyFlag(){
        flag = setFlagValue() //this method written in other class to assign value to the flag
      fun getVal(): Boolean = this.flag // this is to get flag value in other methods static way, like GlobalVariable.getVal()

can you give me some suggestions, thanks.

In general no, booleans are not guaranteed to be threadsafe.

If you’re on the JVM you can use an AtomicBoolean

Thanks, what else can I do just with Kotlin to implement this?

The honest answer is that global mutable state is bad, so you should find a different way of handling this.

If you’re on multiplatform you can try to have a different solution for different targets, on JS all is fine, JVM has atomics, on native, I’m not sure really, there could be an answer here:

1 Like

Shared mutable state and concurrency

The companion object you wrote will work fine if you mark the field @Volatile, as long as setFlagValue() doesn’t call getVal()

The modifyFlag() method seems very strange, though, so I don’t know what you intend to do with it. You should be careful, since lots of programmers fail to achieve thread-safety when using thread-safe methods.