Last active
June 28, 2022 19:19
-
-
Save franciscoafonsoo/9ff79972868096b12759e0b54a26079c to your computer and use it in GitHub Desktop.
Convert a dataclass into another (very similar) dataclass. This can be useful for usecases like you would use unpack in Python, or to make simple changes to an existing object for backwards compatibility. Uses https://kotlinlang.org/docs/reflection.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Heavly based on this post. All credits to the author. | |
// https://www.bezkoder.com/kotlin-convert-object-data-class-to-another/ | |
// build.gradle.kt | |
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.0") | |
// file.kt | |
import kotlin.reflect.full.memberProperties | |
data class Customer( | |
val firstName: String, | |
val lastName: String, | |
val phone: String, | |
val age: Int, | |
val location: String | |
) | |
data class CustomerRecord( | |
val fullName: String, | |
val phone: String, | |
val age: Int, | |
val location: String | |
) | |
fun Customer.toRecord() = with(::CustomerRecord) { | |
val propertiesByName = Customer::class.memberProperties.associateBy { it.name } | |
callBy( | |
args = parameters.associateWith { parameter -> | |
when (parameter.name) { | |
"fullName" -> "$firstName $lastName", | |
// any fields that are different come here | |
else -> propertiesByName[parameter.name]?.get(this@toRecord) | |
} | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment