Abacus/core/src/main/kotlin/org/nwapw/abacus/context/ChainAccumulateDelegate.kt

26 lines
954 B
Kotlin

package org.nwapw.abacus.context
import kotlin.reflect.KProperty
/**
* A delegate to accumulate a collection of elements in a [ReductionContext] hierarchy.
*
* ChainAccumulateDelegate is similar to the [ChainSearchDelegate], however, it operates only on collections.
* Instead of returning the most recent collection, it merges them into a [Set].
*
* @param T the type of element in the collection.
* @property valueGetter the getter used to access the collection from the context.
*/
class ChainAccumulateDelegate<out T>(private val valueGetter: ReductionContext.() -> Collection<T>) {
operator fun getValue(selfRef: Any, property: KProperty<*>): Set<T> {
val set = mutableSetOf<T>()
var currentRef: ReductionContext = selfRef as? ReductionContext ?: return set
while(true) {
set.addAll(currentRef.valueGetter())
currentRef = currentRef.parent ?: break
}
return set
}
}