KStarbound/src/main/kotlin/ru/dbotthepony/kstarbound/util/VirtualProperty.kt

25 lines
861 B
Kotlin

package ru.dbotthepony.kstarbound.util
import com.google.common.collect.ImmutableList
import java.util.stream.Stream
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
class VirtualProperty<R, T>(private val getter: (R) -> T?, private val receivers: ImmutableList<R>) : ReadOnlyProperty<Any?, T?> {
constructor(getter: (R) -> T?, receivers: Stream<R>) : this(getter, receivers.collect(ImmutableList.toImmutableList()))
constructor(getter: (R) -> T?, receivers: Array<out R>) : this(getter, ImmutableList.copyOf(receivers))
constructor(getter: (R) -> T?, receivers: List<R>) : this(getter, ImmutableList.copyOf(receivers))
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
for (receiver in receivers) {
val value = getter.invoke(receiver)
if (value != null) {
return value
}
}
return null
}
}