Is there a way to prohibit changing `latinit` prop...
# announcements
k
Is there a way to prohibit changing
latinit
properties after they've been initialized? Something in the stdlib maybe?
e
can't think of anything in stdlib but building your own is straightforward.
Copy code
class LateInitOnce<T : Any> {
    private lateinit var value: T
    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value
    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        require(!this::value.isInitialized) { "LateInitOnce property has already been initialized" }
        this.value = value
    }
}

val once by LateInitOnce<String>()
once // throws UninitializedPropertyAccessException
once = "first" // ok
once // ok
once = "second" // throws IllegalStateException
@ephemient you beat me to it
e
I didn't look at SO and I like my code better than what's on there anyway :D
😂 3
n
i didn’t look at SO i looked at google and found an answer i accepted
k
Thanks both of you, will go this route... I was thinking if there was anything in the stdlib, such as lazy or observable properties...
👍 1