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. )
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