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()
}
}
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.