Is there a way to define a companion object outside of a class definition in Kotlin?

56 Views Asked by At

As far as I know, one defines a companion object within the class declaration in Kotlin,

class Foo {
    companion object { /* etc etc */ }
}

Suppose class Foo is already defined, without a companion object. Is there a way to equip Foo with a companion object afterwards?

I tried a couple of things;

val Foo.Companion = Foo ()

provokes the error message "extension property cannot be initialized because it has no backing field", and

Foo.Companion = Foo ()

provokes "unresolved reference: Companion".

Is there a way to get some assignment to Foo.Companion to work, such that it would be equivalent to whatever is generated automatically by the compiler in the case of companion object within the class definition?

0

There are 0 best solutions below