Place "static" private method in companion?


#1

Methods that could (but not have to) be static in Java

In Java I make methods not related to any state of the object static, even if the method is private. A static method could be a bit faster (if I remember correctly), but I mainly declare these methods static to express that they are indpendent from any instance state.

Is it common to place such (private) methods in a companion object in Kotlin? Technically speaking these methods wouldn’t be static (as long as they are not decorated with @JvmStatic). Or would you place them beside the other object functions (formerly known as methods)?

Expressed in code:

Usual object function

class MyClass {
    fun doSomethingUseful(x: Int) {
        val y = helper(x)
        ...
    }

    private fun helper(x: Int) = x * 2
}

Function in companion object

class MyClass {
    fun doSomethingUseful(x: Int) {
        val y = helper(x)
        ...
    }

    companion object {
        private fun helper(x: Int) = x * 2
    }
}

(Please ask for permission, if you want to use this code in your own enterprise application. :wink: )

What do you prefer and why?


#2
class MyClass {
    fun doSomethingUseful(x: Int) {
        val y = helper(x)
        ...
    }
}

private fun helper(x: Int) = x * 2

A final method has same performance of a static one, quite same for monomorphic invocation of a regular method, so avoid premature optimization :wink:


#3

As I’ve said that performance optimization is not my primary intention here.


#4

If I have a private function which relates to a class, but not to any particular instance of it, then I always place it in the companion object.

It’s really the only sensible choice. If you place it at the ‘top level’ instead, then it’s no longer private to the class.


#5

As long as you have only one class per file. This should not matter as private at top level means file private. And if you have multiple classes in one file, you should maybe separate them into different files :slight_smile:


#6

I tend to keep my classes small and place related classes in the same file.

Even if i have one class in the file initially, there’s always the possibility that I might add another one.

But, yeah, if you always have only one class per file, top level is as good as companion object.