Skip to content

Instantly share code, notes, and snippets.

@dmcg
Created November 12, 2018 15:24
Show Gist options
  • Select an option

  • Save dmcg/463d7c09a13880625ffebc233164ede8 to your computer and use it in GitHub Desktop.

Select an option

Save dmcg/463d7c09a13880625ffebc233164ede8 to your computer and use it in GitHub Desktop.
Copy a Kotlin data object, applying a transform to every field
@Suppress("UNCHECKED_CAST")
fun <T: Any> T.dataCopy(mapper: (Any?) -> Any?): T {
val memberFunctions = this::class.memberFunctions
val components = memberFunctions.filter { it.name.startsWith("component") }.sortedBy { it.name.substringAfter("component").toInt() }
val componentValues = components.map { it.call(this) }.toTypedArray()
val copyMethod: KFunction<*> = memberFunctions.first { it.name == "copy" }
val copyArgs: List<Any?> = listOf(this) + componentValues.map(mapper)
return copyMethod.call(*copyArgs.toTypedArray()) as T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment