-
-
Save joshrotenberg/932b48c260b1702741f42016bf0a38ac to your computer and use it in GitHub Desktop.
Merge two data classes in Kotlin
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
import kotlin.reflect.full.declaredMemberProperties | |
import kotlin.reflect.full.primaryConstructor | |
/** | |
* Merge two data classes | |
* The resulting data class will contain | |
* - all fields of `other` which are non null | |
* - the fields of `this` for the fields which are null in `other` | |
*/ | |
infix inline fun <reified T : Any> T.merge(other: T): T { | |
val nameToProperty = T::class.declaredMemberProperties.associateBy { it.name } | |
val primaryConstructor = T::class.primaryConstructor!! | |
val args = primaryConstructor.parameters.associate { parameter -> | |
val property = nameToProperty[parameter.name]!! | |
parameter to (property.get(other) ?: property.get(this)) | |
} | |
return primaryConstructor.callBy(args) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment