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

vach

04/12/2017, 10:59 AM
@lupajz this is what i ment
Copy code
class MutableLazy<T>(val supplier : ()-> T) {

   private val mutableOption = MutableOption.empty<T>()

   fun getValue() = mutableOption.ifNotPresentCompute(supplier).get()

   fun setValue(value : T) = mutableOption.take(value)

   fun isInitialized() =  mutableOption.isPresent
}

inline operator fun <T> MutableLazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = getValue()

inline operator fun <T> MutableLazy<T>.setValue(thisRef: Any?, property: KProperty<*>, t: T) {
   setValue(t)
}

var something : String by MutableLazy {
   log("computing this value")
   "default value"
}

fun main(args: Array<String>) {

   something = "manually set value" // comment/uncomment this line...
   println(something)
}
Consider mutable option just like normal option except not immutable... I can simply replace it with any synchronized wrapper of single generic value...
m

marcinmoskala

04/12/2017, 5:20 PM
getValue and setValue can be inside class. It would be faster.
v

vach

04/13/2017, 4:30 AM
yeah i've taken into consideration good ideas from here and came up with this please let me know if any mistakes spotted 🙂 https://gist.github.com/vach/56168a04199e1df580a41e14d2c63f2b
regarding being inside class will be faster, could you explain that? i think extension functions are just static funcitons why would there be an overhead?
If i quote the docs it says
We would like to emphasise that extension functions are dispatched statically, i.e. they are not virtual by receiver type
which as i understand mens at runtime it does not do method lookup, it already knows what to invoke, while with polymorph object it will do method lookup...
4 Views