Legend123
Legend123

Reputation: 378

Kotlin - What is the point of private variables inside private companion objects?

Suppose I have the class

class Foo {
    private companion object {
        private val hello = "world"
    }
}

Is there any point in making Foo.hello private if the companion object is already private?

Upvotes: 3

Views: 2215

Answers (1)

gidds
gidds

Reputation: 18617

I don't think there's a practical difference: hello can be accessed anywhere inside Foo, but nowhere outside it, regardless of whether it's private or not.

However, you might find making it private makes the situation clearer, especially if the companion object is big.  You might find it clarifies the intent.  And it ensures that hello can't be accessed outside, even if the companion object is later changed to be non-private.  So there are slight differences in style.

Upvotes: 8

Related Questions