images from https://www.pexels.com/@katerina-holmes/

Different Approach to Create Mapper using Kotlin Delegated Properties

Randy Arba
3 min readMay 7, 2022

--

This is just another learning path using Kotlin language, last time I focus on Dart language for flutter development. So for this part, I gonna create another mapper using Kotlin delegated properties, if you already know this method you can ignore this article. :D

All developers already know about mapper, this mapper is taken responsibility to transform one data class object into another object, it usually happens on getting data from API response, From API response will map into the specific data that we need instead of getting a bunch of response API data.

How about DTO, the goal remain the same as Mapper, DTOs or Data Transfer Objects is an object that is used to encapsulate data, and send it from one to another. the main benefit of those DTO and Mapper is that it reduces the amount of data that needs to be sent across the wire in distributed applications. So I just using DTO keyword from here. let's start.

As the use-case we use Room integration we need to create Entity data that is used as the name of a table field or insert data into local data. usually, we need to create Entity class and a normal data class, for example, we create ProfileEnitity.class and Profile.class. Normally you will create like this for Mapper

Using function inside Entity class. Profile Entity map into Dto data class properties
Constructor use as a mapper. It maps Entity properties to Dto properties.

Both have same goals, but the second one less code and convient to use. the first one is we must create function inside data class, so every changes of target tranformation will affect the class, we should reduce changes of data domain model, so we need separation, extensions function is come to rescue, we use as the second approach on above DTO sample. Okay but we have another approach to do this, we using delegated properties.

Another approach using delegation to DTO class

Hmmm still look same right? just fancy on the variable properties on ProfileDto class. but wait you should check this out why its have differences compare previous.

Delegated property is not truely properties of those class, its getter and setter is delegated to Entity class. it mean the truely properties still on the Entity class instead on the Dto class. Therefor when Entity property is change, that change is reflected in DTO delegated property, even when Dto was instantiated before the change. in vice versa when Dto delegated property is change, the change is reflected in Entity.

--

--