https://kotlinlang.org logo
c

cy

06/07/2016, 12:02 PM
similar to
Delegates.vetoable
but with exception something like that
Copy code
class AssignOnceDelegate<T>() : ReadWriteProperty<Any?, T> {
    private var value: T? = null
    private var initialized = false

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        if (initialized) {
            return value as T
        }

        throw IllegalStateException("${property.name} not yet initialized")
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        if (initialized) {
            throw IllegalStateException("${property.name} is already initialized")
        }

        this.value = value
        initialized = true
    }
}

class Example {
    var p by AssignOnceDelegate<String>()
}
👍 1