Search code examples
kotlindata-class

Kotlin - Is there a way to pass property values to another object with properties of the same name?


Is there a way to pass property values to another object with properties of the same name to avoid having "repeated" code?

For example, avoid having where CepReceiptsInfo is different class than value but they share some properties name and type :

   val cepReceiptsInfo = CepRecepitsInfo()
    cepReceiptsInfo.operationTimestamp = value.operationTimestamp
    cepReceiptsInfo.sentDate = value.sentDate
    cepReceiptsInfo.sentTime = value.sentTime
    cepReceiptsInfo.concept = value.concept
    cepReceiptsInfo.referenceNumber = value.referenceNumber
    cepReceiptsInfo.amount = value.amount
    cepReceiptsInfo.trackingKey = value.trackingKey
    cepReceiptsInfo.bankTarget = value.bankTarget
    cepReceiptsInfo.bankSource = value.bankSource
    cepReceiptsInfo.sourceClienteName = value.sourceClienteName
    cepReceiptsInfo.beneficiaryName = value.beneficiaryName
    cepReceiptsInfo.accountNumberTarget = value.accountNumberTarget
    cepReceiptsInfo.term = value.term
    cepReceiptsInfo.authorizationNumber = value.authorizationNumber
    cepReceiptsInfo.linkCep = value.linkCep
    cepReceiptsInfo.status = value.status
    cepReceiptsInfo.bankSourceRefund = value.bankSourceRefund
    cepReceiptsInfo.causeRefund = value.causeRefund
    cepReceiptsInfo.accountTargetRefund = value.accountTargetRefund
    cepReceiptsInfo.currency = value.currency
    cepReceiptsInfo.accountNumberSource = value.accountNumberSource
    cepReceiptsInfo.accountTypeSource = value.accountTypeSource
    cepReceiptsInfo.accountTypeTarget = value.accountTypeTarget
    cepReceiptsInfo.indicatorRefund = value.indicatorRefund
    cepReceiptsInfo.amountIntRefund = value.amountIntRefund
    cepReceiptsInfo.operationRefundTimestamp = value.operationRefundTimestamp
    cepReceiptsInfo.dateMovement = value.dateMovement
    cepReceiptsInfo.timeMovement = value.timeMovement
    cepReceiptsInfo.dateRefund = value.dateRefund
    cepReceiptsInfo.timeRefund = value.timeRefund

to something like f.e.:

val cepReceiptsInfo = CepReceintsInfo()
cepReceiptsInfo.assignFrom(value)

both Classes are data classes.


Solution

  • I don't know of a way without reflection.

    fun Any.assignFrom(other: Any) {
        val thisProperties = this::class.memberProperties
            .filterIsInstance<KMutableProperty<*>>()
            .map { it.name to it }
            .toMap()
        for (property in other::class.memberProperties){
            thisProperties[property.name]?.setter?.call(this, property.getter.call(other))
        }
    }