0
votes

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

1 Answers

0
votes

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