Why private members of companion objects are visible to the class?

I was a bit surprised when i found out that private members of companion objects are visible to the class, e.g to some member function within the class.

class A {
    
    companion object {
        
        private val x = 5
    }

    fun someMemberFunction() = x // x is visible here
}

But if we have an normal object, it’s private members are not visible outside of object itself (as i expected):

class A {
    
    object B {
        
        private val x = 5
    }

    fun someMemberFunction() = B.x // x is not visible here
}

How can we argue that these two very similar concepts differ in this way?

In Java, C#, C++, Ruby, Smalltalk, etc. for an instance method of a class some private static var inside the same class is also visible.

I begin to understand. We have access to private members of companion objects within a class because these objects are designed in particular to simulate static access through the class name. And companion object is initialized when the corresponding class is loaded. On the other hand normal nested object is initialized when accessed first time, i.e. it is not bound to the outer class.

2 Likes

Thanks bro. I was having same doubt since long.