4

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.

htafoya
  • 18,261
  • 11
  • 80
  • 104

1 Answers1

3
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()
Enselic
  • 4,434
  • 2
  • 30
  • 42