Skip to content

Instantly share code, notes, and snippets.

@kingori
Last active August 28, 2018 08:51
Show Gist options
  • Save kingori/d26d7de57038f15e37781721fbf0fa88 to your computer and use it in GitHub Desktop.
Save kingori/d26d7de57038f15e37781721fbf0fa88 to your computer and use it in GitHub Desktop.
kotlin data class copy by reflection
import org.junit.Assert
import org.junit.Test
import kotlin.reflect.KProperty
class DataClassTest {
@Test
fun copyObj() {
val data= Data1(1, "b", Value(3))
Assert.assertEquals( Data2(1,"b",Value(3)) , data.toData2())
Assert.assertEquals(Data2(1, "b", Value(3)), copyDataObj<Data1, Data2>(data))
}
}
inline fun <S: Any,reified T: Any> copyDataObj( source:S) :T {
val sourceMap: Map<String, Any?> =
source::class.members
.filter { it is KProperty }
.map { it.name to (it as KProperty).getter.call(source) }
.fold(mutableMapOf()) { acc, pair ->
acc[pair.first] = pair.second
acc
}
val constructor = T::class.constructors.first()
val args = constructor.parameters.fold( mutableListOf<Any?>()) { acc, param ->
acc.add( sourceMap[param.name])
acc
}
return constructor.call(*args.toTypedArray())
}
data class Value(val v:Int)
data class Data1( val a:Int, val b:String, val v:Value) {
fun toData2() = Data2( a,b,v)
}
data class Data2( val a:Int, val b:String, val v:Value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment