Creating a mutable variable in a singleton results...
# kotlin-native
a
Creating a mutable variable in a singleton results in the following warning:
Copy code
object MySingleton {
    private var testingVar = false
}
Variable in singleton without @ThreadLocal can't be changed after initialization.
On annotating with @ThreadLocal results in error:
@ThreadLocal is applicable only to top level declarations
Is this intended or a bit misleading?
t
annotate your entire object, not the field
a
@Tijl Hey, Thanks! If I annotate the whole object, then what about the immutable
val
fields, would they be different from different threads?
t
yes
😞 1
a
So, putting them on top level will be better? I mean I don't want my immutable variables to hold different references local to the thread.
t
You’re trying to make a global variable, which is usually not a good idea so I’d encourage you to think about your design. However, you can check out AtomicBoolean from Kotlin native (use expect/actual to access it, or the stately library)
a
Ohh thanks, atomic types seems to be perfect here, though there's no AtomicBoolean I'd probably use AtomicInt 🙂
t
Ah yes it’s a util class in Stately
keep in mind that on the JVM cross thread access is not atomic by default either, you need at least
@Volatile
👍 1