Skip to content

Instantly share code, notes, and snippets.

@MichalBrylka
Created July 31, 2022 21:49
Show Gist options
  • Save MichalBrylka/0dc8b1b8d9e1657d029920af95a231cb to your computer and use it in GitHub Desktop.
Save MichalBrylka/0dc8b1b8d9e1657d029920af95a231cb to your computer and use it in GitHub Desktop.
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) }
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