Kotlin Generic Extension Functions
This quick guide to writing generic extension functions in Kotlin is useful for calling functions based on your default value's types.
Join the DZone community and get the full member experience.
Join For FreeI have been educating myself in Kotlin recently, and one of the most powerful features that Kotlin provides is extension functions. The simplest example of an 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 the 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, the above code allows us to fetch (dynamically) values of a property, SOME_CONFIG_PROP_NAME
in this example, and provide a 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 the String
class because property names are always of the 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
}
}
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 the appropriate function based on the type of the default value.
So now our code can become as simple as:
"some.config.name".getConfig("I am a good default value")
"call.external.service".getConfig(false)
Boom. Done.
Published at DZone with permission of Ravi Hasija, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments