https://kotlinlang.org logo
#announcements
Title
# announcements
a

Ashutosh Panda

12/09/2019, 12:11 PM
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

diesieben07

12/09/2019, 12:13 PM
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

Ashutosh Panda

12/09/2019, 12:14 PM
Like static members are shared by each object so does this happen with companion object
d

diesieben07

12/09/2019, 12:14 PM
Since objects are singletons, you will have a similar effect.
a

Ashutosh Panda

12/09/2019, 12:15 PM
Lets say there is count property in companion object will there be same copy of count for each object
d

diesieben07

12/09/2019, 12:16 PM
the property does not exist on objects of the class. It only exists on the companion object
a

Ashutosh Panda

12/09/2019, 12:16 PM
pardon me
d

diesieben07

12/09/2019, 12:16 PM
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

Ashutosh Panda

12/09/2019, 12:18 PM
lets say I introduce a method in companion object to increment sharedProp by 1 whenever a new object is created ,Is it possible
d

diesieben07

12/09/2019, 12:19 PM
Yes, you could do so:
Copy code
class Foo {
  init {
    // short for: Companion.instanceCount++
    instanceCount++ 
  }
  companion object {
    var instanceCount: Int = 0
  }
}
a

Ashutosh Panda

12/09/2019, 12:22 PM
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

diesieben07

12/09/2019, 12:22 PM
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

Ashutosh Panda

12/09/2019, 12:23 PM
anything i miss?
d

diesieben07

12/09/2019, 12:24 PM
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

Ashutosh Panda

12/09/2019, 12:26 PM
Ok I think I have understood please add anything which may have been missed in discussion
27 Views