I'm looking to add lambdas to a queue to be run when the queue is polled, using the arguments passed to them when they were added to the queue. Something like below:
@FunctionalInterface
public interface Movement {
Deque<Movement> movementDeque = new ArrayDeque<>();
void move(MovementType type);
}
...
public void addToQueue(Direction direction){
MovementType type = switch (direction) {
case LEFT -> MovementType.TURN_LEFT;
case RIGHT -> MovementType.TURN_RIGHT;
case UP -> MovementType.FORWARD;
case DOWN -> MovementType.BACKWARD;
}
Movement.movementDeque.offer((m) -> subject.move(type));
}
...
Movement.movementDeque.poll(); // Running the lambda later
Is this possible? None of what I've attempted so far seems to allow me to invoke lambdas using the arguments passed to them when they were defined. Feel like I'm misunderstanding something pretty fundamental here.
I dont think its possible to store a lambda with specific paramaters (since remember, a lambda is essentially just a shorthand method), what you could do though, is change the move method to not take any arguments
public interface Movement {
void move();
}
And then you can simply queue the move method and invoke it like so
public void addToQueue(Direction direction){
MovementType type = switch (direction) {
case LEFT -> MovementType.TURN_LEFT;
case RIGHT -> MovementType.TURN_RIGHT;
case UP -> MovementType.FORWARD;
case DOWN -> MovementType.BACKWARD;
}
Movement.movementDeque.offer(() -> subject.move(type));
}
Runnable movement = movementDeque.poll();
movement.run();
Which should achieve the same result you are expecting