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)
.
Companion object is an object that is not related to any particular instance of
MyClass
, therefore it cannot access the instance propertymyVar
and instance functionmyFunc
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: