- Published on
Copying Beans With Kotlin
- Yair Mark
I discovered the idea for these til (Today I Learnt) posts from a colleague. The aim is to write a short post that takes you no longer than 5 minutes to put together.
The post helps you reflect on something you have learned during the course of your work day. The idea being that often a day goes by and you look back not realizing what you accomplished, this helps you reflect and solidify anything you learnt.
Today I had to take an object returned by a view projection and modify one of its fields for the front-end for display purposes. The bean was fairly large weighting in at about 8 fields. The problem was that the service that returned this object was used in a number of places. Changing it at the service level would have potentially broken some other downstream process that uses this. It also made the most sense to modify the object at the exit point of the system to keep the internal business domain consistent.
I initially went with the novel approach of instantiating a new object and assigning fields from the previous one into the new one and only modifying what I needed.
val transaction1 = Transaction(currency = "USD", amount = 10.25476, reference = "4499E58E-96D7-4B04-A601-F84A335D6E73") val roundedAmount = roundToTwoDecimals(transaction1.amount) val transactionWithRoundedAmount = Transaction(currency = transaction1.currency , amount = roundedAmount , reference = transaction1.reference)
Luckily as you have gathered by now we are using Kotlin in our project and the particular bean I was working on was just that, a simple bean. So I simply made it a data class and used the following (which data classes get):
val transaction1 = Transaction(currency = "USD", amount = 10.25476, reference = "4499E58E-96D7-4B04-A601-F84A335D6E73") val roundedAmount = roundToTwoDecimals(transaction1.amount) val transactionWithRoundedAmount = transaction1.copy(amount = roundedAmount)
This may not seem like much but on a larger bean this makes a huge difference. It is less error prone and much easier to see which parts of the object have changed.
- Kotlin Data Classes https://kotlinlang.org/docs/reference/data-classes.html#copying