0

In Kotlin, we can access function or property of companion object using class name as following:

class DemoClass {
    companion object {
        fun someFunction() {}
    }
}

// Accessing function
DemoClass.someFunction()

But how can I access the same function if I have an object of DemoClass?

class DemoClass {
    companion object {
        fun someFunction() {}
    }
}

val demoObj = DemoClass()

// I cannot do following - It will not compile.
demoObj.someFunction() 

Basically, I want to access companion function using class object.

Dhaval
  • 2,724
  • 2
  • 24
  • 33
  • 3
    Why do you want to do this? Why can't you just do `DemoClass.someFunction()`? – Sweeper Mar 06 '22 at 08:13
  • 2
    `someFunction()` is a companion object, so not related to an instance of `DemoClass`. – Madhu Bhat Mar 06 '22 at 10:39
  • Try calling `DemoClass.someFunction()`. Companion Object is static reference. To access the function, method or varaible inside companion object no need to create class instance. – Gobinath Nataraj May 17 '22 at 12:41
  • Does this answer your question? [how to access companion object from object instance in kotlin?](https://stackoverflow.com/questions/46827060/how-to-access-companion-object-from-object-instance-in-kotlin) – sschuberth Aug 16 '22 at 07:06

0 Answers0