`val A.extVal get() = B(this)` Is there a way to n...
# announcements
e
val A.extVal get() = B(this)
Is there a way to not construct
B
every time I reference to
A.extVal
? Given that I don't own class
A
.
m
I tried using the
lazy
-delegate, but it didn't work because you don't have access to
this
inside the function you pass to it. I guess you could create your own version of the
lazy
-delegate that passes the receiver object as a parameter to the function though.
This kinda works, but it is not thread safe:
Copy code
class LazyExtension<V, T>(val f: V.() -> T) {
    data class Result<T>(val t: T)
    var result: Result<T>? = null
    
    operator fun getValue(thisRef: V, property: kotlin.reflect.KProperty<*>): T {
        return result?.t ?: Result(thisRef.f()).also { 
            result = it
        }.t
    }
}
👍 2
e
Wow thanks man, I will take a look
m
I fixed it up a little bit so it doesn't use that
tmp
variable.
i
@marstran Note that this implementation of LazyExtension would return the same value for any receiver after it had been initialized. Probably not what the author wanted.
m
Ah, that's true. You would also need to keep track of all the receivers.
I guess that could turn out to be quite a memory leak if it is used a lot.