https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Karlo Lozovina

08/13/2020, 3:05 PM
memory wise, are companion object more efficient? will all class instances share a single companion object or is a separate one created for every instance?
s

spand

08/13/2020, 3:07 PM
The companion object is a singleton
n

nanodeath

08/13/2020, 3:08 PM
all `object`s are singletons, including the
companion
kind
k

Karlo Lozovina

08/13/2020, 3:19 PM
so if I have this inside a class constructor:
Copy code
val foobar = object {
  val x = "x"
}
all of the instances will share the same object?
d

Dominaezzz

08/13/2020, 3:19 PM
Oh, that's an anonymous object.
☝️ 1
All instances will have a unique object.
k

Karlo Lozovina

08/13/2020, 3:20 PM
oh, so every instanc will have it's uqnie thing
right, right! thanks!
s

Shawn

08/13/2020, 3:22 PM
if you want to declare a companion object, the syntax looks like this:
Copy code
class Foo {
  companion object {
    val x = "x"
  }
}
all instances of
Foo
will have a reference to that same companion object