Access methods outside companion object - Kotlin

alessandro gaboardi picture alessandro gaboardi · Apr 3, 2017 · Viewed 14.8k times · Source

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

Answer

yole picture yole · Apr 3, 2017

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() 
    }
}