androidfunctionkotlincompanion-objectkotlin-companion

Kotlin - What does companion object fun do?


Declaring a "static" function in Kotlin is done using:

companion object {
    fun classFoo() {
        //do something
    }
}

However I was mistakenly coding

companion object fun classFoo() {
     //do something
}

Expecting the code to do the same, if only one static function was required.

The compiler doesn't argue about that, and it seems to be valid as the compiler expects a fun name and parameters. But I never found how to call that function from other class.

What does that form of companion object fun do? there is no doc available about that.


Solution

  • class Test {
        companion object fun classFoo() {
            //do something
        }
    }
    

    is equivalent to

    class Test {
        companion object // Add "{ }" to make it explicit that the object body is empty
    
        fun classFoo() {
            //do something
        }
    }
    

    i.e. a class with an empty companion object (which is valid syntax) and a normal member function, callable in the usual way:

    Test().classFoo()