Search

Kotlin generic extension functions

I have been educating myself in Kotlin recently. One of the most powerful feature that Kotlin provides is: Extension Functions. The simplest of example of a Extension Function that I can come up with is:

fun String.addOne() = this + "1"

And then: println("Boba".addOne()) leads to an output of: Boba1

So above we have added a new function to String class.

Generic Extension Functions

With the basic introduction out of the way, I wanted to write a Generic extension function. We use Netflix OSS at work and are constantly getting property values via code that looks like this:

Kotlin would know based on the input param what "type" it is. And we can use that power to use the when expression along with is to check what type it is and call appropriate function based on the type of default value.