Skip to content

Instantly share code, notes, and snippets.

@Takhion
Created September 16, 2018 16:23
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Takhion/48d5434490421edb7276e919f94aeeb5 to your computer and use it in GitHub Desktop.
Kotlin property delegate utils
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private typealias GetValue<This, R> = (thisRef: This, property: KProperty<*>) -> R
private typealias SetValue<This, R> = (thisRef: This, property: KProperty<*>, value: R) -> Unit
inline fun <This, R> property(
crossinline getValue: GetValue<This, R>
) =
object : ReadOnlyProperty<This, R> {
override fun getValue(thisRef: This, property: KProperty<*>) = getValue(thisRef, property)
}
inline fun <This, R> property(
crossinline getValue: GetValue<This, R>,
crossinline setValue: SetValue<This, R>
) =
object : ReadWriteProperty<This, R> {
override fun getValue(thisRef: This, property: KProperty<*>) = getValue(thisRef, property)
override fun setValue(thisRef: This, property: KProperty<*>, value: R) = setValue(thisRef, property, value)
}
import kotlin.reflect.KProperty
import kotlin.SinceKotlin
private typealias ProvideDelegate<This, Delegate> = (thisRef: This, property: KProperty<*>) -> Delegate
@SinceKotlin("1.1") // provideDelegate
interface PropertyDelegateProvider<This, Delegate : Any> {
operator fun provideDelegate(thisRef: This, property: KProperty<*>): Delegate
}
@SinceKotlin("1.1") // provideDelegate
inline fun <This, Delegate : Any> propertyDelegate(
crossinline provideDelegate: ProvideDelegate<This, Delegate>
) =
object : PropertyDelegateProvider<This, Delegate> {
override fun provideDelegate(thisRef: This, property: KProperty<*>) = provideDelegate(thisRef, property)
}
import kotlin.properties.Delegates
import kotlin.properties.ReadWriteProperty
// top-level
val sampleGet: String by property { thisRef, property -> "" }
var sampleSet: String by property({ thisRef, property -> "" }, { thisRef, property, value -> })
val sampleProvideGet by propertyDelegate<Nothing?, Lazy<String>> { thisRef, property -> lazy { "" } }
var sampleProvideSet by propertyDelegate<Nothing?, ReadWriteProperty<Nothing?, String>> { thisRef, property -> Delegates.notNull() }
class InsideClass {
val sampleGet: String by property { thisRef, property -> "" }
var sampleSet: String by property({ thisRef, property -> "" }, { thisRef, property, value -> })
val sampleProvideGet by propertyDelegate<InsideClass, Lazy<String>> { thisRef, property -> lazy { "" } }
var sampleProvideSet by propertyDelegate<InsideClass, ReadWriteProperty<InsideClass, String>> { thisRef, property -> Delegates.notNull() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment