Would it be possible to have an option to pass the...
# language-proposals
Would it be possible to have an option to pass the enclosing class as a weak reference to lambdas? Pretty much like swift does with
[weak self]
You can already create a
and consume it from the lambda. I'd try something like
Copy code
with(WeakReference(this)) {
    // Code containing lambda
I have no idea if that's working, though, as coding in Slack never does any good :) To my knowledge, if you don't reference enclosing class instance,
doesn't get captured. So is it really needed on a language syntax level?
Hmm.... interesting proposal. I'm rather unsure if this can do what Swift's
[weak self]
does, but I'll try to work on some examples and see what's the outcome.
What is your use case for weak reference? Because on my practice weak references are very rare outside of caching and other specific use cases, just because there is GC on JVM, so cyclic references is not a problem (like it is in Swift/ObjC) and if we talking about callbacks or similar use cases, when you want to avoid leaking imo explicit clearing/disposing is better option Also, if you use them a lot for some reason you already can use delegates or some extension functions to simplify usage even further
My use case would go in the direction of callbacks. Just recently in an android project i needed to pass a ResultReceiver to a service via an Intent and needed to make sure that this wouldn't leak an activity. The solution was a not very elegant workaround, definitely more cumbersome to read than a simple
[weak self]
in the beginning of a lambda.
Do you have some code snippet with your existing version of code?
Well, what basically was my problem as well as what solution i chose is described here: https://stackoverflow.com/questions/4510974/using-resultreceiver-in-android/4549639 If you're really interested in what the working code looks like, you can find the commit containing my code here: https://github.com/LPeteR90/Catroid/commit/0d1e2a5d4fe9a24156733996f2e2c426f1fdf31d. The relevant parts are in the classes ProjectUploadActivity, ProjectUploadService and ResultReceiverWrapper. Disclaimer in advance: Some of the source code may be designed in an a little bit weird way, since this is a project developed by computer science students with little experience.