16
votes

I'm pretty new to kotlin and I was wondering if it's possible, and if it's against best practice to access methods and variables that are outside a companion object, from within the companion object.

For example

class A {
    fun doStuff(): Boolean = return true

    companion object{
        public fun stuffDone(): Boolean = return doStuff()
    }
}

or something like that

Thank you

2
Is doStuff defined on the top level or inside the class that owns the companion object?marstran

2 Answers

33
votes

doStuff() is an instance method of a class; calling it requires a class instance. Members of a companion object, just like static methods in Java, do not have a class instance in scope. Therefore, to call an instance method from a companion object method, you need to provide an instance explicitly:

class A {
    fun doStuff() = true

    companion object {
        fun stuffDone(a: A) = a.doStuff() 
    }
}
1
votes

You can also call functions that are outside of companion object block.

class A {
    fun doStuff() = true

    companion object {
        val a = A()
        fun stuffDone() = a.doStuff() 
    }
}