Kotlin set variable and call method in main class from companion object

1.1k Views Asked by At

I'm new to Kotlin, and I don't understand if/how I can call a function or set a variable from the companion object:

class MyClass {
    public var myVar: Boolean
    public fun myFunc(): Int { ... }

    companion object {
        private fun doStuff(){
            myVar = true
            myFunc(1)
        }        
    }   
}

I get unresolvedReference on myVar = true and myFunc(1).

1

There are 1 best solutions below

0
On

Companion object is an object that is not related to any particular instance of MyClass, therefore it cannot access the instance property myVar and instance function myFunc without specifying the instance. It just does not know which instance it should access.

If you really want to do that from a function in the companion object, you should pass it an instance of MyClass as well:

companion object {
    private fun doStuff(instance: MyClass){
        instance.myVar = true
        instance.myFunc(1)
    }        
}