Skip to content

Instantly share code, notes, and snippets.

@franciscoafonsoo
Last active June 28, 2022 19:19
Show Gist options
  • Save franciscoafonsoo/9ff79972868096b12759e0b54a26079c to your computer and use it in GitHub Desktop.
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
// 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