Kotlin converter extension function

Bal sikandar
MindOrks
Published in
2 min readJan 13, 2020
Photo by Francis Nie on Unsplash

What are converters?

Converter methods are methods which we use to transform one object into another

For example Integer.parseInt(str), String.valueOf() etc.. These methods help us transform one object to another. Well in these examples we are converting one object type to another.

But In this article, we’ll talk about converters which we use to transform API objects to Database objects.

Terminologies

For simplicity, we’ll use Weather object

  • WeatherAPI — Object received from the server
  • WeatherDB — Object to be stored in Database
  • Weather —Object meant to be used everywhere in the app

Fundamentally all three are the same object but it’s a good practice to separate them for the following reasons as explained in the next paragraph.

Why we need them?

  • Suppose WeatherAPI has over fifty fields but we only need five then we can use a converter method to trim it before saving in a local database.
  • If one object changes then we only need to update converter methods so the rest of the objects are unaffected.
  • Abstraction i.e. expose only what’s necessary.

Writing converter methods in Kotlin using extension functions

Let’s look at the Weather object for API and Database and extension function to convert one into another.

//WeatherAPI object
data class
WeatherAPI(
val id: Long,
val humidity: Int,
val description: String,
val weatherId: Int,
val windDeg: Double,
val windSpeed: Double,
val temperature: Int
)
//WeatherDB object
data class
WeatherDB(
val temperature: Int,
val windSpeed: Double,
val humidity: Int
)

Extension method to convert WeatherAPI to WeatherDB object

fun WeatherAPI.toWeatherDB() = WeatherDB(
temperature = temperature,
windSpeed = windSpeed,
humidity = humidity
)

Now just call toWeatherDB() extension function with WeatherAPI object to get WeatherDB object as below

val weatherDB: WeatherDB = WeatherAPI(...).toWeatherDB()

Similarly, we can also create toWeather() extension function to convert WeatherDB to Weather object.

So go ahead and change your converters and if you’re not using them then start using them because A little abstraction never hurts.

Thanks for reading this article. Be sure to 👏 recommend this article if you found it helpful. It means a lot.

Also let’s connect on twitter, github and linkedin.

Clap, share if you like it and follow me for my next move.

--

--

Bal sikandar
MindOrks

Android developer @shuttl Ex @_okcredit. Blogger | Open source contributor https://about.me/balsikandar.