DEV Community

Cover image for I ❤ Kotlin, inline function edition
Andrew Emerson
Andrew Emerson

Posted on • Updated on • Originally published at andrewemerson.io

I ❤ Kotlin, inline function edition

This post was also published on my personal site at andrewemerson.io

Over the last year, I have been exclusively writing new Android code (and converting old code) in Kotlin. It's such an expressive, succint and fun (excuse the fun pun) language to write with. I won't go into all the reasons right now plus many others have written about this before.

Today I want to share a small snippet which demonstrates a recent warm and fuzzy feeling I got writing in Kotlin.

I have been working on a requirement to measure network calls in our app using an OKHttp NetworkInterceptor and log the stats to our analytics platform.

The obvious way to write this is something like this (code is simplified):

fun intercept() {
        // ...
        val start = SystemClock.elapsedRealtime()
        val result = doSomethingWeWantToMeasure()
        val duration = SystemClock.elapsedRealtime() - start
        log(duration)
        // ...
}

This works fine but the meat of the function's logic is polluted with measurement code making it harder for your colleagues to grok what's going on.

Enter inline generic function with lambda

Here's how an inline function can help this code:

fun intercept() {
        // ...
        val result = measure { doSomethingWeWantToMeasure() }
        // ...
}

inline fun <T> measure(action: () -> T) {
        val start = SystemClock.elapsedRealtime()
        val result = action()
        val duration = SystemClock.elapsedRealtime() - start
        log(duration)
        return result
}

Better, no? Now I can concentrate on reading what the intercept() function's main intention is without skipping over lines of measurement code. We also benefit from the option of reusing that code in other places where we want to profile performance.

What is inline?

I am still quite new to this so this may not be 100% for the experts but my simple explanation is:

inline allows you to call a function with a lambda argument within a closure ({ ... }) rather than passing the lambda like measure(myLamda).

You can read the longer, more technical (and possibly more accurate) explanation here.

In the mean time, happy Kotlin-ing and feel free to ask questions or add your favourite Kotlin warm-and-fuzzies in the comments.

Top comments (0)