Skip to content

Instantly share code, notes, and snippets.

@mattsplat
Last active August 11, 2023 15:32
Show Gist options
  • Save mattsplat/b07c28884195c53313f934c1e731c8a7 to your computer and use it in GitHub Desktop.
Save mattsplat/b07c28884195c53313f934c1e731c8a7 to your computer and use it in GitHub Desktop.
Copy Class
/**
* Create new class with values from original unless passed in changes map
*/
inline fun <reified T: Any> T.replicateWithChanges(
changes: Map<String, Any?> = mapOf()
): T {
val constructor = this.javaClass.kotlin.primaryConstructor
if(constructor?.parameters == null) throw Exception("Invalid Constructor for Replication")
val propertyMap = this.mapProperties()
val paramMap : Map<KParameter, Any?> = constructor.parameters.associateWith { param ->
val value = if (changes.containsKey(param.name)) {
changes[param.name]
} else {
if (propertyMap.containsKey(param.name)) propertyMap[param.name] else null
}
value
}.toMap()
return constructor.callBy(paramMap)
}
/**
* Create key map of class properties
*/
inline fun <reified T: Any> T.mapProperties() : Map<String, Any?> {
return this.javaClass.kotlin.declaredMemberProperties.associate { field ->
field.isAccessible = true
Pair(field.name, field.get(this))
}
}
/**
* Usage
*
* data.replicateWithChanges(mapOf("propertyName" to newValue))
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment