Hi everyone, I have a question. Is Kotlin Reflecti...
# getting-started
t
Hi everyone, I have a question. Is Kotlin Reflection a strong reference or a weak reference?
j
Kotlin Reflect is a library to inspect the structure of the code at runtime, it's not a reference. What exactly are you referring to from this library?
t
I am thinking about if I retrieve the resource string from ViewModel (I know this is the wrong way but I am just thinking). So if I pass the activity context into the ViewModel, it may lead to a memory leak, right? But if I pass the context::getString instead? Does it still make memory leak happens?
j
Ah. So you're asking whether function references capture their receiver as a weak or strong reference. I am not 100% sure, but I would say it's a strong reference that prevents garbage collection. The function reference would need to become unreachable itself for the context to be eligible for garbage collection.
e
a function reference has a tiny bit more magic than a lambda:
{ Unit } != { Unit }
but
obj::func == obj::func
,
{ Unit }.name
doesn't exist but
obj::func.name
does but in all other ways, it behaves like a lambda
a lambda holds a strong reference to everything it captures
t
Thank you, guys! Very useful to me. 🫡