M
M
marmuff2020-05-24 19:34:36
Android
marmuff, 2020-05-24 19:34:36

Kotlin, generics and mappers: is it worth it?

Good day to all.
In the course of writing a small SDK for the customer's API in the Android Library Module, I became too lazy to describe 100500 data-class mappers from the data-layer to the domain-layer and the idea came to use generics - namely, to create some of the following simple construction:

object SDKMapper {

    @Suppress("UNCHECKED_CAST")
    fun <T, F> map(data: F, to: Class<T>): T = to.getDeclaredConstructor(to).newInstance(data)

}


And in each data-class, if necessary, implement the method constructors in the form:

constructor(data: MyResponseDTO) {
    // some code here with values set to fields
}


And in the future call a la:

fun getResponse(): MyResponse = SDKMapper.map(repository.getResponse(), MyResponse::class.java)


I wanted to hear the opinion of more experienced developers - is it worth doing this, is it a bad or good practice?
For not always what saves time does not worsen the quality of the code.

UPD: Updated SDKMapper to inline mapping implementation and switched to constructors

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question