Skip to content

Instantly share code, notes, and snippets.

@remylavergne
Last active October 29, 2020 07:51
Show Gist options
  • Save remylavergne/8c85b238f96dc70fb74c4760d34aaf85 to your computer and use it in GitHub Desktop.
Save remylavergne/8c85b238f96dc70fb74c4760d34aaf85 to your computer and use it in GitHub Desktop.
Kotlin - Composition with Delegation / Reflection - Two ways
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.full.memberProperties
fun main() {
// Create Sup
val spiderman: SuperHeroe = SuperHeroe(Person(firstname = "Peter", lastname = "Parker", age = 28), "SpiderMan")
println("Spiderman firstname: ${spiderman.firstname}")
println("Spiderman lastname: ${spiderman.lastname}")
println("Spiderman age: ${spiderman.age}")
println("Spiderman supname: ${spiderman.supname}")
}
data class Person(
var firstname: String,
var lastname: String,
var age: Int
) {
inline operator fun <reified T> getValue(spiderman: SuperHeroe, property: KProperty<*>): T {
val prop = this.javaClass.kotlin.memberProperties.find { it.name == property.name }
if (prop != null) {
return prop.get(this) as T
}
throw RuntimeException()
}
operator fun <T> setValue(spiderman: SuperHeroe, property: KProperty<*>, s: T) {
// Recherche de la propriété
val prop = this::class.members.find { it.name == property.name }
// Set de la valeur
if (prop is KMutableProperty<*>) {
prop.setter.call(this, s)
} else {
throw RuntimeException()
}
}
/**
* Easy way without reflection matching properties
*/
/*
inline operator fun <reified T> getValue(o: Any, property: KProperty<*>): T {
return when (property.name) {
"firstName" -> this.firstname
"lastName" -> this.lastname
"age" -> this.age
else -> throw RuntimeException()
} as T
}
operator fun <T> setValue(o: Any, property: KProperty<*>, s: T) {
when (property.name) {
"firstName" -> this.firstname = s as String
"lastName" -> this.lastname = s as String
"age" -> this.age = s as Int
else -> throw RuntimeException()
}
}
*/
}
data class SuperHeroe(
var person: Person,
var supname: String
) {
var firstname: String by person
var lastname: String by person
var age: Int by person
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment