https://kotlinlang.org logo
Title
m

Mike R

08/04/2019, 11:21 PM
I'd like to implement a queue of functions where a function can be added, called after x seconds, then removed. I don't want to have to specify what arguments are provided at call-time, but rather when they are being added to the queue... I believe I can define the queue like
val queue: Queue<() -> Unit> = LinkedList()
, but I don't think the Queue type will do what I need as I described above. Any recommendations?
d

Dominaezzz

08/04/2019, 11:24 PM
That should do the trick.
queue.add({ callMethod(arg0, arg2) })
m

Mike R

08/04/2019, 11:34 PM
Wouldn't
callMethod
be executed as soon as I run that?
At least from my experience with Python, if I wanted to pass around a function I would just refer to it like
someFunction
, but as soon as I do
someFunction()
it gets called
m

Mark Murphy

08/04/2019, 11:36 PM
In Dominic's solution, the queue is not holding the results of calling
callMethod()
-- the queue is holding a lambda expression that calls
callMethod()
(note the
{}
wrapping
callMethod(arg0, arg2)
)
callMethod()
will not be called until you
invoke()
the lambda expression. Your queue would still be
Queue<() -> Unit>
from a data type standpoint, where
() -> Unit
is a function type saying "no parameters and return nothing", which is what that lambda expression does.
m

Mike R

08/04/2019, 11:36 PM
Ahhhhh!!!!
Okay, that is so crafty. Nice!!!
Now... what would happen if I needed to accept functions with an unknown amount and type of args, as well as return type? Would I want to utilize generics in that case?
m

Mark Murphy

08/04/2019, 11:39 PM
Well, the queue and its lambda expressions would not necessarily change.
Queue<() -> Unit>
neither knows nor cares what code is in the lambda expressions. Those can be as simple or as complicated as you need.
m

Mike R

08/04/2019, 11:39 PM
Ahh - got it - right, the Queue now cares about the lambda itself, not the function it contains, therefore that will work! Perfect 🙂
Thank you so much @Mark Murphy and @Dominaezzz!!
👍 1