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

edwardwongtl

09/19/2017, 8:39 AM
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

marstran

09/19/2017, 9:06 AM
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

edwardwongtl

09/19/2017, 10:22 AM
Wow thanks man, I will take a look
m

marstran

09/19/2017, 10:49 AM
I fixed it up a little bit so it doesn't use that
tmp
variable.
i

ilya.gorbunov

09/19/2017, 10:52 AM
@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

marstran

09/19/2017, 10:54 AM
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.