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:
DynamicPropertyFactory.getInstance().getStringProperty("SOME_CONFIG_PROP_NAME", "I am a good default value").get()
Basically, above code allows us to fetch (dynamically) values of a property: SOME_CONFIG_PROP_NAME
in this example, and provide default value I am a good default value
in this case.
We have several variations of this, for example:
DynamicPropertyFactory.getInstance().getIntProperty
DynamicPropertyFactory.getInstance().getFloatProperty
DynamicPropertyFactory.getInstance().getDoubleProperty
DynamicPropertyFactory.getInstance().getLongProperty
DynamicPropertyFactory.getInstance().getBooleanProperty
So on and so forth. I wanted to have a generic extension function available on String
class because property names are always String
type. Here's the generic function:
fun String.getConfig(default: T): T {
val dynamicPropertyFactory = DynamicPropertyFactory.getInstance()
return when (default) {
is String -> dynamicPropertyFactory.getStringProperty(this, default).get()
is Int -> dynamicPropertyFactory.getIntProperty(this, default).get()
is Float -> dynamicPropertyFactory.getFloatProperty(this, default).get()
is Double -> dynamicPropertyFactory.getDoubleProperty(this, default).get()
is Boolean -> dynamicPropertyFactory.getBooleanProperty(this, default).get()
is Long -> dynamicPropertyFactory.getLongProperty(this, default).get()
else -> default
} as T
}
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.
So now our code can become as simple as:
"SOME_CONFIG_PROP_NAME".getConfig("I am a good default value")
"CallExternalService".getConfig(false)
Boom. Done.