Fix WriteOnce not properly handling nulls

This commit is contained in:
DBotThePony 2024-10-27 10:35:20 +07:00
parent e2d4f810d4
commit b832873203
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -1,17 +1,19 @@
package ru.dbotthepony.mc.otm.core.util
import ru.dbotthepony.kommons.util.KOptional
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class WriteOnce<V>(private val customMessage: String? = null) : ReadWriteProperty<Any?, V> {
private var value: V? = null
private var value: KOptional<V> = KOptional()
override fun getValue(thisRef: Any?, property: KProperty<*>): V {
return checkNotNull(value) { customMessage ?: "Property ${property.name} is not initialized" }
value.ifPresent { return it }
throw IllegalStateException(customMessage ?: "Property ${property.name} is not initialized")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: V) {
check(this.value == null) { "Property ${property.name} is already initialized" }
this.value = value
this.value.ifPresent { throw IllegalStateException("Property ${property.name} is already initialized") }
this.value = KOptional(value)
}
}