Created
July 31, 2022 21:49
-
-
Save MichalBrylka/0dc8b1b8d9e1657d029920af95a231cb to your computer and use it in GitHub Desktop.
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
interface Changeable | |
infix fun <TTarget : Changeable, TProperty> Changeable.withChanged(change: Pair<kotlin.reflect.KProperty1<TTarget, TProperty>, TProperty>): Changeable = | |
this.also { | |
val (property, newValue) = change | |
val field = it::class.java.getDeclaredField(property.name) | |
field.isAccessible = true | |
field.set(it, newValue) | |
} | |
fun <TTarget : Changeable> Changeable.withChanged(vararg changes: Pair<kotlin.reflect.KProperty1<TTarget, Any>, Any>): Changeable = | |
this.also { for (change in changes) it.withChanged(change) } | |
fun <TTarget : Changeable> Changeable.withChanged(changes: Iterable<Pair<kotlin.reflect.KProperty1<TTarget, Any>, Any>>): Changeable = | |
this.also { for (change in changes) it.withChanged(change) } |
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
fun main() { | |
val p = Person("Mike", 38, 15.0) | |
println(p) | |
p withChanged (Person::age to 99) | |
println(p) | |
p.withChanged((Person::age to 999), (Person::name to "ABC")) | |
println(p) | |
val changes = arrayListOf<Pair<kotlin.reflect.KProperty1<Person, Any>, Any>>((Person::age to 9999), (Person::name to "DDDDD")) | |
p.withChanged(changes) | |
println(p) | |
} | |
data class Person(val name: String, val age: Int, val salary: Double) : Changeable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment