mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Sunday, 27 June, 2021

Kotlin: Type conversion with adapters

In this post we will learn how we can use Kotlin extension functions to provide a simple and elegant type conversion mechanism.

Maybe you have used Apache Sling before. In this case, you are probably familiar with Slings usage of adapters. We will implement a very similar approach in Kotlin.

Creating an extension function

With Kotlins extension functions we can add methods to existing classes. The following declaration adds an adaptTo() method to all sub types of Any.

inline fun <reified T : Any> Any.adaptTo(): T {
    ..
}

The generic parameter T parameter specifies the target type that should be returned by the method. We keep the method body empty for the moment.

Converting an Object of type A to another object of type B will look like this with our new method:

val a = A("foo")
val b = a.adaptTo<B>()

Providing conversion rules with adapters

In order to implement the adaptTo() method we need a way to define conversion rules.

We use a simple Adapter interface for this:

interface Adapter {
    fun <T : Any> canAdapt(from: Any, to: KClass<T>): Boolean
    fun <T : Any> adaptTo(from: Any, to: KClass<T>): T
}

canAdapt(..) returns true when the implementing class is able to convert the from object to type to.

adaptTo(..) performs the actual conversion and returns an object of type to.

Searching for an appropriate adapter

Our adaptTo() extension function needs a way to access available adapters. So, we create a simple list that stores our adapter implementations:

val adapters = mutableListOf<Adapter>()

Within the extension function we can now search the adapters list for a suitable adapter:

inline fun <reified T : Any> Any.adaptTo(): T {
    val adapter = adapters.find { it.canAdapt(this, T::class) }
            ?: throw NoSuitableAdapterFoundException(this, T::class)
    return adapter.adaptTo(this, T::class)
}

class NoSuitableAdapterFoundException(from: Any, to: KClass<*>)
    : Exception("No suitable adapter found to convert $from to type $to")

If an adapter is found that can be used for the requested conversion we call adaptTo(..) of the adapter and return the result. In case no suitable adapter is found a NoSuitableAdapterFoundException is thrown.

Example usage

Assume we want to convert JSON strings to Kotlin objects using the Jackson JSON library. A simple adapter might look like this:

class JsonToObjectAdapter : Adapter {
    private val objectMapper = ObjectMapper().registerModule(KotlinModule())

    override fun <T : Any> canAdapt(from: Any, to: KClass<T>) = from is String

    override fun <T : Any> adaptTo(from: Any, to: KClass<T>): T {
        require(canAdapt(from, to))
        return objectMapper.readValue(from as String, to.java)
    }
}

Now we can use our new extension method to convert a JSON string to a Person object:

data class Person(val name: String, val age: Int)

fun main() {
    // register available adapter at application start
    adapters.add(JsonToObjectAdapter())

    ...
    
    // actual usage
    val json = """
        {
            "name": "John",
            "age" : 42
        }
    """.trimIndent()

    val person = json.adaptTo<Person>()
}

You can find the source code of the examples on GitHub.

Within adapters.kt you find all the required pieces in case you want to try this on your own. In example-usage.kt you find some adapter implementations and usage examples.

Leave a reply