6

There are can be two ways of writing helper method in Kotlin

First is

object Helper {
    fun doSomething(a: Any, b: Any): Any {
        // Do some businesss logic and return result
    }
}

Or simply writing this

fun doSomething(a: Any, b: Any): Any {
    // Do some businesss logic and return result
}

inside a Helper.kt class.

So my question is in terms of performance and maintainability which is better and why?

Abhishek
  • 2,295
  • 24
  • 28

2 Answers2

6

In general, your first choice should be top-level functions. If a function has a clear "primary" argument, you can make it even more idiomatic by extracting it as the receiver of an extension function.

The object is nothing more than a holder of the namespace of its member functions. If you find that you have several groups of functions that you want to categorize, you can create several objects for them so you can qualify the calls with the object's name. There's little beyond this going in their favor in this role.

object as a language feature makes a lot more sense when it implements a well-known interface.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
4

There's a third and arguably more idiomatic way: extension functions.

fun Int.add(b: Int): Int = this + b

And to use it:

val x = 1
val y = x.add(3) // 4

val z = 1.add(3) // 4

In terms of maintainability, I find extension functions just as easy to maintain as top-level functions or helper classes. I'm not a big fan of helper classes because they end up acquiring a lot of cruft over time (things people swear we'll reuse but never do, oddball variants of what we already have for special use cases, etc).

In terms of performance, these are all going to resolve more or less the same way - statically. The Kotlin compiler is effectively going to compile all of these down to the same java code - a class with a static method.

Todd
  • 30,472
  • 11
  • 81
  • 89
  • 1
    See also: [When should one prefer Kotlin extension functions?](https://stackoverflow.com/questions/35317940/when-should-one-prefer-kotlin-extension-functions) – hotkey Aug 16 '18 at 14:24