Created
November 12, 2018 15:24
-
-
Save dmcg/463d7c09a13880625ffebc233164ede8 to your computer and use it in GitHub Desktop.
Copy a Kotlin data object, applying a transform to every field
This file contains hidden or 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
| @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