What's the difference between using a `Companion O...
# getting-started
v
What's the difference between using a
Companion Object
and using an
Object Declaration
?
s
companion objects are the closest thing Kotlin has to the notion of static members - they’re declared inside of a class and a single one is instantiated to be referenced to by every instance of said class
v
Do Object Declarations not allow me do the same? -> "Call a method without instantiation"
s
an object declaration is just a way to create a new anonymous class instance, which are often used to implement interfaces on the fly
so this
Copy code
class Foo {
  companion object {
    fun bar() {}
  }
}
is rather different from this
Copy code
class Foo {
  val fieldObject = object {
    fun bar() {}
  }
}
the former allows you to call
Foo.bar()
, the latter does not
e
If you dont need the class, put
fun
out of a class… it will belong to package without a class and is static. It’s more “kotlin-way”
🔝 1
v
You mean
object
?
I get it now... This helped:

https://youtu.be/buhk5TRX_rw

Thanks
s
I believe @earroyoron is referring to what’s known as “top-level” functions
e
right @Shawn