Hi can anyone please explain me what is companion ...
# announcements
a
Hi can anyone please explain me what is companion object and how it is related to static members and static methods( I know C++)
d
A companion object is a singleton (like normal objects in Kotlin). Additionally the methods and properties in a companion object can also be accessed by just the class's name. But the companion object can be passed around (it's an actual instance), it can implement interfaces, etc.
a
Like static members are shared by each object so does this happen with companion object
d
Since objects are singletons, you will have a similar effect.
a
Lets say there is count property in companion object will there be same copy of count for each object
d
the property does not exist on objects of the class. It only exists on the companion object
a
pardon me
d
Example:
Copy code
class Foo(val instanceProp: Int) {
   companion object {
      var sharedProp: Int = 3
   }
}
val instance = Foo(5)
println(instance.instanceProp) // 5
printn(Foo.sharedProp) // 3
a
lets say I introduce a method in companion object to increment sharedProp by 1 whenever a new object is created ,Is it possible
d
Yes, you could do so:
Copy code
class Foo {
  init {
    // short for: Companion.instanceCount++
    instanceCount++ 
  }
  companion object {
    var instanceCount: Int = 0
  }
}
a
So basically what you are saying is that companion object's members and methods have one copy for all objects and methods could be called without any object
Tell me if I miss something
d
They don't have a copy. The companion object is a singleton (only once instance of it exists). Therefor all the properties in it also only exist once.
a
anything i miss?
d
First start with normal objects:
Copy code
class Foo {
   init {
      MyObject.instanceCount++
   }
}

object MyObject {
   var instanceCount = 0
}
Companion objects operate the exact same way, the only difference is that you can call them by the containing class's name
a
Ok I think I have understood please add anything which may have been missed in discussion