aboutsummaryrefslogtreecommitdiff
path: root/shared/src/commonMain/kotlin/mx/trackermap/TrackerMap/client/infrastructure/ApplicationDelegates.kt
blob: 7b913445d08a0af93187a9921a0adf4525ee3d46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package mx.trackermap.TrackerMap.client.infrastructure

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

object ApplicationDelegates {
    /**
     * Provides a property delegate, allowing the property to be set once and only once.
     *
     * If unset (no default value), a get on the property will throw [IllegalStateException].
     */
    fun <T> setOnce(defaultValue: T? = null): ReadWriteProperty<Any?, T> = SetOnce(defaultValue)

    private class SetOnce<T>(defaultValue: T? = null) : ReadWriteProperty<Any?, T> {
        private var isSet = false
        private var value: T? = defaultValue

        override fun getValue(thisRef: Any?, property: KProperty<*>): T {
            return value ?: throw IllegalStateException("${property.name} not initialized")
        }

        override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) {
            if (!isSet) {
                this.value = value
                isSet = true
            }
        }
    }
}