blog podcast

Kotlin Extension Methods

If you’ve worked for a while with Java and then take the step into Kotlin, it is easy to keep on writing code like you used to do it in Java but just using Kotlin’s more succinct syntax. That’s also a very good first step to getting into the world of Kotlin. Once you’ve gotten some experience there’s one feature I really advice you to adopt. That’s the Extension Methods.

I knew the feature first from the C# world where it was introduced and used as a powerful tool to be able to keep C# backword compatible while at the same time extending the api with new useful functions. But the tool is not only for people that are developing frameworks. Also you can use it to patch frameworks you are using with functionality that saves you from writing stupid boilerplate code. I’ll give you an example: In Vertx there is no synchronized get function on Futures. That makes sense because the idea of Vertx is to write async code. But sometimes you might want to write unit tests, and there it’s very useful to access futures in a synchronized manner. Now, with this little code snipped:

fun <T> Future<T>.get(): T {
    val latch = java.util.concurrent.CountDownLatch(1);
    this.onComplete {
        latch.countDown()
    }
    latch.await(3, TimeUnit.SECONDS);
    if(latch.count > 0) {
        throw RuntimeException("Timeout, waited for more than 3 seconds for a reply.")
    }
    if (this.failed()) {
        throw this.cause()
    }
    return this.result()
}

you suddenly have the synchronicity you need, and no need to duplicate any boilerplate across tests.