Search code examples
androidkotlinobjectsingletonvar

Problems accessing var in kotlin object (singleton)


Having this object:

object BarManager {
    private var bars = mutableMapOf<String, Bar>()
}

Can't access bars like this:

BarManager.bars[name]

It gives me this error:

Cannot access 'bars': it is private in 'BarManager'

Supposedly, as per the Kotlin Properties and Fields documentation, each mutable (i.e., var) property has a getter and setter automatically created for it. Therefore there's no reason to auto generate getters and setters for Kotlin code.

So... whats happening here?


Solution

  • The visibility you put in front of the property is the visibility of those generated accessors, not the backing fields. Backing fields are always private (and only directly usable outside accessors when using the K2 compiler; will be official in Kotlin 2.0). Exception to this is when you mark the property with @JvmInline, but this doesn't change how the property is treated in Kotlin code, only how it is compiled and seen from Java code.

    So when you put private var, that means the getter and setter are both private. Remove the private keyword to make your getter and setter public (the default visibility).