com.github.squirrelgrip.util.InitOnceProperty.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-extensions Show documentation
Show all versions of kotlin-extensions Show documentation
A collection of useful kotlin extensions
package com.github.squirrelgrip.util
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
@Suppress("UNCHECKED_CAST")
class InitOnceProperty : ReadWriteProperty {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: Any, property: KProperty<*>): T {
if (value == EMPTY) {
throw IllegalStateException("Value isn't initialized")
}
return value as T
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
if (this.value != EMPTY) {
throw IllegalStateException("Value is initialized")
}
this.value = value
}
}
inline fun initOnce(): ReadWriteProperty = InitOnceProperty()