Static function in companion vs in a file


#1

I wondering what are the guidelines for implementing a static function:

  • Inside a companion object

class Foo() {
val blah blah

companion object {
fun doSth(){
}
}
}

  • Just write the function in the file out of the class.

fun doSth(){
}
class Foo() {
val blah blah
}

How to distinguish when to follow any of the above implementations?


#2

Top-level functions are more accessible: they are added to a package instead of a class. (private are added to the file)

Therefor, if you want a function to be very accible, it need to be a top-level function.
This is the case if you would normally put it in an utility-class.

If you on the other hand don’t want the function to show up every time you press autocomplete, use companion-object. This is also for functions that must belong to the class, like create() or buildFrom(), because they are senseless if you call them without class.

This is just the way i use them

See also


#3

In general companion methods are better than global functions since global functions bloat the default namespace. You should use global function either in case of small projects (not libraries!) or for something which will be frequently used.