Closures and event handling: Correct Solution


Suppose we are in an environment where CLICK, TICK, and KEY events can occur, and we have the following functions available:

onClick(closure)

Executes closure after every subsequent CLICK event.

onKeyPress(closure)

Executes closure after every subsequent KEY event.

afterDelay(tickCount, closure)

Executes closure once after exactly tickCount TICK events have occurred.

twice(closure)

Immediately executes closure two times.

Multiple closures can be registered to handle the same event. If this happens, they execute in the order they were registered.


Part 1

Consider the following code:

A
afterDelay(3, () -> {
    B
    onKeyPress(() -> C);
    D
});
E
twice(() -> {
    F
    onClick(() -> G);
    H
});
I
onClick(() -> J);
K

Write out the order in which all the marked statements will execute given the following sequence of events (showing both the marked statements and the event names):

TICK
CLICK
TICK
TICK
TICK
TICK
KEY
KEY
CLICK

Solution

A
F
F

TICK

CLICK
G
G
J

TICK

TICK

TICK
B

TICK

KEY
C

KEY
C

CLICK
G
G
J

AFTER
E
H
H
I
K
D

Part 2

Consider the following code:

public class StatefulPuzzle {
    private int x = 0;

    public void run() {
        onClick(() -> {
            x++;
            System.out.println("x=" + x);
        });

        if (x < 2) {
            onClick(() -> {
                System.out.println("Hi!");
            });
        }

        onClick(() -> {
            if (x < 2) {
                System.out.println("Bye!");
            }
        });

        System.out.println("End of run()");
    }
}

Given a call to run() followed by two CLICK events, what would this code print?

Solution

End of run()
x=1
Hi!
Bye!
x=2
Bye!

Related puzzles: