name.remal.gradle_plugins.dsl.utils.WriteOnceProperty.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gradle-plugins-kotlin-dsl Show documentation
Show all versions of gradle-plugins-kotlin-dsl Show documentation
Remal Gradle plugins: gradle-plugins-kotlin-dsl
package name.remal.gradle_plugins.dsl.utils
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.reflect.KProperty
fun writeOnce() = WriteOnceProperty()
fun writeOnce(onWrite: (value: T) -> Unit) = WriteOnceProperty(onWrite)
class WriteOnceProperty(private val onWrite: (value: T) -> Unit) {
constructor() : this({})
private val isInitialized = AtomicBoolean(false)
private lateinit var value: T
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
if (isInitialized.compareAndSet(false, true)) {
this.value = value
onWrite(value)
} else {
throw IllegalStateException("Property ${property.name} has already been initialized")
}
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value
}
}