androidkotlinconvertersapache-commonskotlin-multiplatform

common fields converting from one class to another from parent class


I have 2 classes inherited from parent class, now i have data in 1 class, how to convert into other class which are having similar fields

ex: class1{ var x,var y }:Parent()

class2{ var a,var b }:Parent()

class Parent( var l,var m )

Now I have data fetched from server into class1, but in UI im using class2 due to my business logic reasons, one thing is direct copying but it will create lot of boiler plate code and maintenance will be problem if new fields are added in future

I used apache BeanUtils.copyProperties(class1Obj, class2Obj) but it is not supported in Kotlin Multiplatform Setup, is there any similar library like this or only option is to copy paste everything


Solution

  • After R&D this is the solution I have found:

    fun copyProperties(source: Parent, target: Parent) {
        var properties = Parent::class.memberProperties
        for (property in properties) {
            if (property is KMutableProperty<*>) {
                property.setter.call(target, property.getter.call(source))
            }
        }
    }
    

    Here we iterate through the properties of the parent class and use reflection to copy the values from the source object to the target object.

    Passing the name of the parent class doesn't makes it a generic class. Thus if we have 10 places for copying different classes, we have to use different methods.