DEV Community

Cover image for Kotlin for better helper methods
Ernesto λrroyo
Ernesto λrroyo

Posted on

Kotlin for better helper methods

When implementing helper classes in Kotlin you can, compared to Java, take advantage of a less verbose and more powerful idiomatic style.

Let’s check this easy but verbose Java example; the method body is not important...

package io.earroyoron.helpers;

public class EarroyoronHelper {

/* A private constructor to avoid class instantiation */
 private EarroyoronHelper() {}

/* Just some helper method */
 public static String doSomething
 (final String a, final String b) {
 //.... whatever
   return a + " and then " + b;
 }
}

Too many things just for such a simple thing, isn’t it?

The Kotlin version just shows what a modern language is:

package io.earroyoron.helpers

/* Just some helper method */
 fun andThen (a: String, b: String): String {
 return"$a and then $b"
 }
}

We don’t need things that, actually, does not add value or improve the intention or readiness.

  • Of course the ; that is useless
  • The class, as we will not instantiate it. Kotlin adds the function (method) to the package namespace. You can import as:

import io.earroyoron.helpers.andThen

the method could indeed return directly the response as in:

fun andThen (a: String, b: String) = "$a and then $b"

Even better with extensions

A better version uses class extensions:

package io.earroyoron.helpers

fun String.doSomeTransformation (b: String) = "$this and then $b"

So you can call this helper as:

"original string".andThen ("more letters")

infix

or if you add infix to the function ( infix fun ) to improve as a DSL style:

infix fun String.doSomeTransformation (b: String) = "$this and then $b"

val sillyString = "original string" andThen "more letters"

This is the most kotlin idiomatic way; you may use object to instantiate a singleton, or companion class to have an static block in a not-singleton class but both are not the perfect way.

Functional style

As you are not creating the object and the method is just an static one, with only depending on the input parameters to produce the results you are using a functional style. Is a plus.

Top comments (0)