Object reference delegate

This commit is contained in:
2024-05-06 19:48:28 +02:00
parent 7a8d1cac62
commit 5fe320581b
3 changed files with 20 additions and 20 deletions

View File

@@ -2,16 +2,20 @@ package nl.astraeus.nl.astraeus.persistence.reference
import nl.astraeus.nl.astraeus.persistence.Persistable
import nl.astraeus.nl.astraeus.persistence.currentTransaction
import java.io.Serializable
import kotlin.reflect.KProperty
inline fun <reified T : Persistable> reference(
) = Reference(T::class.java)
class Reference<S : Persistable>(
val cls: Class<S>,
val setter: (Long?) -> Unit,
val getter: () -> Long?,
) {
val cls: Class<S>
) : Serializable {
var id: Long? = null
operator fun getValue(thisRef: Persistable, property: KProperty<*>): S? {
return currentTransaction()?.find(cls.kotlin, (getter() ?: 0L))
return currentTransaction()?.find(cls.kotlin, id ?: 0L)
}
operator fun setValue(thisRef: Persistable, property: KProperty<*>, value: S?) {
@@ -19,7 +23,7 @@ class Reference<S : Persistable>(
// todo: only store if not already stored?
currentTransaction()?.store(value)
}
setter(value?.id)
id = value?.id
}
companion object {