All Downloads are FREE. Search and download functionalities are using the official Maven repository.

name.remal.gradle_plugins.dsl.utils.WriteOnceProperty.kt Maven / Gradle / Ivy

There is a newer version: 1.9.2
Show newest version
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
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy