Tianyu Zhu
06/02/2021, 4:03 PMKProperty
as a key in a Map
?
• Is KProperty
created compile-time? or is it created by reflection at runtime?
• Will this cause memory leaks?
For context I've defined the following:
abstract class Mixin<Value> {
private val mixins = mutableMapOf<KProperty<*>, Value>()
companion object Property {
operator fun <Value, T: Value> getValue(mixin: Mixin<Value>, property: KProperty<*>): T {
return when (val value = mixin.mixins[property]) {
null -> throw NoSuchElementException("Uninitialized mix-in: ${property.name}")
else -> @Suppress("UNCHECKED_CAST") (value as T)
}
}
operator fun <Value> setValue(mixin: Mixin<Value>, property: KProperty<*>, value: Value) {
mixin.mixins[property] = value
}
}
}
The idea is that, by extending this class, I get to make type-safe property extensions on classes that extend `Mixin`:
// A dynamically extensible class declared in some parent module
class Shipment(id: String): Mixin<Any>
// Now, let's say I want to do track shipment status in some downstream module.
var Shipment.statusHistory: List<ShipmentStatus> by Mixin // declare the mixin
// Load the status history of the shipment from the database
fun Shipment.loadStatusHistory() {
statusHistory = statusDatabase.lookup(id)
}
// Check if the shipment is complete
val Shipment.isComplete: Boolean get() = statusHistory.any { it.state == ShipmentStatus.State.COMPLETE }