Untitled.kt
# announcements
s
Untitled.kt
a
This sounds like a XY problem, what are you trying to achieve?
e
lazy
in Kotlin is just a wrapper around underlying type, so basically if you want your variable to be
lazy
, it needs to be
Lazy<String>
.
by
keyword just delegates
get
function to something else (in this case - to
Lazy
instance, which is acquired by calling
by readWriteLazy...
.
s
I'm trying to work around a bug in a 3rd party library that has a by lazy var that does something horribly inefficient, and I want to replace the var.
a
You can't replace the var as it is, all you can do is work around it e.g. add an extension-function and use that instead of the property
where does
readWriteLazy
come from?
r
try
var foo by readWriteLazy { "b" }
s
I just realized that readWriteLazy is not part of stdlib. It is
internal fun <T> readWriteLazy(initializer: () -> T): ReadWriteProperty<Any?, T> = ReadWriteLazyVal(initializer)
Which goes down a rabbit hole of other stuff defined in this library.
I fixed the underlying issues, so I no longer want to do this.
Although out of curiosity, I guess I still have the same question. Why can't I replace the lazy initializer on a var after initialization?
e
@sbyrne I answered earlier. Because function
readWriteLazy
returns wrapper around the value, which abstracts over access to this value, making it lazy.
by
keyword just delegates access to this wrapper, leaving the value intact
a
@sbyrne I guess they left it out because you could change how the internals of a class works and thus get surprising behaviors afterwards