Merge objects in Kotlin if they are updated I am very new to Kotlin and I am trying to achieve this:


I get a batch of PersonDetails to save or update
In the batch, the same PersonDetails with name is different locale can be present.
The end goal of this method is to merge the batch itself and also merge the existing entries in Database then return the updated data structure for saving into DB. 


I am not very happy with the way I have coded, can you please review this code and give your review comments.

fun doProcess(batchToProcess: List&lt;PersonDetail&gt;) : Map&lt;Long, PersonDetail&gt; {
    val idsInBatch = batchToProcess.map { it.lcmId }.toList()
    val personDetailsFromDb = personDetailsRepository.getBatch(idsInBatch)
        .map { it.lcmId to it }
        .toMap()

    val batchesOfPersonDetails = mutableMapOf&lt;Long, PersonDetail&gt;()

    batchToProcess.map { aPerson -&gt;
        var personDetail = batchesOfPersonDetails[aPerson.lcmId]
        if (personDetail == null) {
            personDetail = personDetailsFromDb[aPerson.lcmId]
        }

        val updatedPersonDetail = when {
            personDetail == null -&gt; aPerson.toPersonDetail()

            personDetail.isActive != aPerson.isActive -&gt; {
                personDetail.isActive = personDetail.isActive
                personDetail
            }

            personDetail.localeDetails[aPerson.localeCode] != aPerson.localeName -&gt; {
                personDetail.localeDetails[aPerson.localeCode] = aPerson.localeName
                personDetail
            }

            else -&gt; {
                logger.info { "Duplicate_Event for id ${aPerson.lcmId}" }
                personDetail
            }
        }

        batchesOfPersonDetails[updatedPersonDetail.lcmId] = updatedPersonDetail
    }

    return batchesOfPersonDetails
}
To make your code understandable, you should extract the code for merging a single PersonDetail into a separate function:

fun merge(fresh: PersonDetail, fromDb: PersonDetail): PersonDetail {
}


This function is where the main complexity happens, and it should be easy to write unit tests for this part of the code. And you should definitely write unit tests, after all you're dealing with details of actual people here, so you better get it correct from the beginning.

In this merge function you can have much shorter variable names. Since you are dealing with persons only, you can remove the word person from the variable names, like I already did in the function declaration above. You can remove the word detail as well.