Hey, is there some way to check if a lazy variable...
# getting-started
a
Hey, is there some way to check if a lazy variable is initialized without using reflections?
s
You mean like this?
Copy code
val lazy: Lazy<String> = lazy { "foo" }
val isInitialized = lazy.isInitialized()
a
Yes
s
The above will work fine but obviously doesn't work with property delegation
So what you can't do is
Copy code
val lazy: String by lazy { "foo" }
val isInitialized = lazy.isInitialized() // doesn't work
😢 1
a
Alright I will try it, thanks.
s
A compromise would be something like
Copy code
val lazyFoo: Lazy<String> = lazy { "foo" }
val foo by lazyFoo
val fooIsInitialized = lazyFoo.isInitialized()
j
Also whatever you do with this information will suffer from the same concurrency issues that
lazy
is saving you from
💯 2
👍 1
s
I suppose technically you could write
Copy code
val foo: String by lazy { "foo" }
val isInitalized = (::foo.getDelegate() as Lazy<*>).isInitialized()
but I wouldn't recommend it (and it doesn't help with the concurrency issue)
a
The code isn't going to be multithreaded so I doubt it's a big deal
j
Could you please share your use case for needing this in the first place?
a
I'm not super sure if I even need this in the first case, but it's for a UI Component system. The superclass has 5 separate ArrayLists per component for each and every "listener" (e.g. MousePressed, MouseEntered etc...) but I might not use all of the listeners for each component, and since some screens might be initializing 100+ components, it might create a frame drop when opening the screen.
Of course, this could just be an oversight on my behalf, and I'm overcomplicating this, and it is unnecessary.
y
maybe it would be a good idea to use a
lateinit var
instead? because with that you may do
object::propertyName.isInitialized
and under the hood it doesn't actually use reflection
👍 1
j
5 separate ArrayLists per component for each and every "listener"
Not sure I understand the cardinality here. Is that: • 5 arraylists per component per listener? In that case what is the 5 here? • 1 arraylist per component per listener, and there are 5 listeners per component? In any case, what are the elements of those lists? And are those lists
lazy
properties themselves or are the lists regular properties but containing lazy items?
Also, you have somewhat described your need for
lazy
, but not the need for knowing that the lazy is initialized. This is mostly what I'm interested in (in case it's an XY problem)
a
An array would be like
val mousePressedListener = ArrayList<UIComponent.() - Unit>()
And, yeah I should have presented my problem, and then what my attempted solution was instead of what I did.