commonMain.entity.optional.delegate.OptionalDelegate.kt Maven / Gradle / Ivy
package dev.kord.common.entity.optional.delegate
import dev.kord.common.entity.optional.Optional
import kotlin.js.JsName
import kotlin.jvm.JvmName
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty
public fun KMutableProperty0>.delegate(): ReadWriteProperty =
object : ReadWriteProperty {
override fun setValue(thisRef: Any?, property: KProperty<*>, value: V?) {
val optional = if (value == null) Optional.Missing()
else Optional.Value(value)
[email protected](optional)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): V? {
return when (val optional = [email protected]()) {
is Optional.Value -> optional.value
is Optional.Missing, is Optional.Null<*> -> null
}
}
}
public fun KMutableProperty0>>.delegateList(): ReadWriteProperty> =
object : ReadWriteProperty> {
override fun setValue(thisRef: Any?, property: KProperty<*>, value: List) {
val optional = if (value.isEmpty()) Optional.Missing()
else Optional.Value(value)
[email protected](optional)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): List {
return when (val optional = [email protected]()) {
is Optional.Value -> optional.value
is Optional.Missing, is Optional.Null<*> -> emptyList()
}
}
}
@JvmName("provideNullableDelegate")
@JsName("provideNullableDelegate")
public fun KMutableProperty0>.delegate(): ReadWriteProperty =
object : ReadWriteProperty {
override fun getValue(thisRef: Any?, property: KProperty<*>): V? {
return [email protected]().value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: V?) {
[email protected](Optional(value))
}
}