I have a few jobs in a class that I would like to ...
# announcements
s
I have a few jobs in a class that I would like to set to null can cancel, but obviously this doesn't work, I get a
val cannot be reassigned
error, i think because i don't want to assign the local value in the forEach closure, but the property of the parent class. How could I do something like this?
Copy code
listOf<Job?>(
            uiJob,
            authJob,
            videoEventsJob,
            videoJob,
            countdownJob
        ).forEach {
            it?.cancel()
            it = null
        }
e
you should call
map
instead and then deal with the output list
e
there's also
.mapNotNull { ... }
which is equivalent to
.map { ... }.filterNotNull()
c
setting the local variable`it`would not have any effect. If your code would work, you would have `null`ed all elements in the list - you can throw it away then anyways.
var l = listOf<Job?>...map( it?.cancel() )
could work, depending of what
cancel()
returns.
z
IIUC those names you’re passing to listOf are class properties, and you’re just using listOf to avoid copy/pasting the cancel+null code? If so, I think this is over engineered - just copy/pasting two lines for every field is much simpler. You could get this to work by passing around property references, but now you’re both creating lists (wasteful but probably not terrible) and using reflection (pretty expensive, esp on Android) just to save a bit of typing and that seems like the wrong trade off.
s
yeah I think I'm in step with @Zach Klippenstein (he/him) [MOD]. Thanks for the input everyone 🙌