TwoClocks
11/13/2020, 9:00 PMCasey Brooks
11/13/2020, 9:02 PMlazy { }
property is what you’re looking for https://kotlinlang.org/docs/reference/delegated-properties.html#lazyNir
11/13/2020, 9:02 PMNir
11/13/2020, 9:03 PMNir
11/13/2020, 9:04 PMNir
11/13/2020, 9:07 PMIrving Rivas
11/13/2020, 9:09 PMRyan
11/13/2020, 9:10 PMIrving Rivas
11/13/2020, 9:11 PMRyan
11/13/2020, 9:11 PMTwoClocks
11/13/2020, 9:28 PMNir
11/13/2020, 9:28 PMTwoClocks
11/13/2020, 9:28 PMTwoClocks
11/13/2020, 9:29 PMNir
11/13/2020, 9:42 PMIrving Rivas
11/13/2020, 10:23 PMlazy
may do the job, if it’s not something that gets used on the UI thread and you can just block in the lambda.andreasmattsson
11/14/2020, 6:17 AMprivate lateinit var
and expose it outwardly with a public val getter?
class Example1 {
private lateinit var _value: Any
val value get() = _value
}
If the value is set the first time from outside the class I don't see how the compiler could know which assignment is first, in order to disallow others.
If what you are merely concerned with the value changing after the fact you could make later assignments no-op, either with internal logic, or with a delegate:
fun <T> setOnce(
accessBeforeSet: () -> T = throw IllegalStateException("Value not yet set"),
setAgain: (previousValue: T) -> T = throw IllegalStateException("Value has already been set")
) = object : ReadWriteProperty<Any?, T> {
@Volatile private var value: T? = null
override operator fun getValue(thisRef: Any?, property: KProperty<*>) = value ?: accessBeforeSet()
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = this.value?.let(setAgain) ?: value
}
}
class Example2 {
private var value by setOnce<Any>(setAgain = {
it // USE PREVIOUS VALUE
})
}
Regardless, relying on network logic for a temporal order of initialization without making the uninitialized state outwardly visible strikes me as a generally bad idea. I would in that case follow @Nir's advice and refactor the code to avoid the situation even if it is more code. I find sealed classes are often a good fit if there are a finite number of states (e.g. uninitialized or initialized with value).