https://kotlinlang.org logo
#announcements
Title
# announcements
m

marcinmoskala

04/12/2017, 10:34 PM
@vach
Copy code
fun <T> mutableLazy(initializer: () -> T): ReadWriteProperty<Any?, T> = MutableLazy<T>(initializer)

private class MutableLazy<T>(val initializer : ()-> T): ReadWriteProperty<Any?, T> {

   private var value: T? = null
   private var initialized = false

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

   override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
       this.value = value
       initialized = true
   }
}
👍 2
v

vach

04/13/2017, 2:19 AM
Thanks, this is good for unsafe lazy, single thread use. My version uses Modified optional, which takes care of the concurrency 🙂 especially when it needs to get the value from init safe way...
but private class is better idea 🙂 i'll improve my solution