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(1, () -> {
    B
    twice(() -> {
        C
        onKeyPress(() -> {
            D
        });
        E
    });
    F
    afterDelay(1, () -> {
        G
        onKeyPress(() -> H);
        I
    });
    J
});
K
afterDelay(3, () -> {
    L
    onKeyPress(() -> {
        M
        onKeyPress(() -> {
            N
        });
        O
    });
    P
    afterDelay(2, () -> Q);
    R
});
S
afterDelay(4, () -> {
    T
    afterDelay(1, () -> {
        U
        onKeyPress(() -> {
            V
        });
        W
    });
    X
    onKeyPress(() -> Y);
    Z
});
AA
onClick(() -> AB);
AC
onKeyPress(() -> {
    AD
    onKeyPress(() -> {
        AE
        onKeyPress(() -> {
            AF
        });
        AG
    });
    AH
    afterDelay(2, () -> {
        AI
        onKeyPress(() -> {
            AJ
        });
        AK
    });
    AL
});
AM

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):

KEY
KEY
TICK
KEY
TICK
KEY
KEY
TICK
KEY
TICK
TICK
TICK
TICK
TICK
KEY
TICK

Solution

A

KEY
AD

KEY
AD
AE

TICK

KEY
AD
AE
AE
AF

TICK
B
C
C

KEY
AD
AE
AE
AF
AE
AF
AF
D
D

KEY
AD
AE
AE
AF
AE
AF
AF
D
D
AE
AF
AF
AF

TICK
AI
AI

KEY
AD
AE
AE
AF
AE
AF
AF
D
D
AE
AF
AF
AF
AE
AF
AF
AF
AF
AJ
AJ

TICK
L
AI
G

TICK
T
AI
AI

TICK
AI

TICK
Q
U

TICK

KEY
AD
AE
AE
AF
AE
AF
AF
D
D
AE
AF
AF
AF
AE
AF
AF
AF
AF
AJ
AJ
AE
AF
AF
AF
AF
AF
M
AJ
H
Y
AJ
AJ
AJ
V

TICK

AFTER
K
S
AA
AC
AM
AH
AL
AH
AL
AG
AH
AL
AG
AG
E
E
F
J
AH
AL
AG
AG
AG
AH
AL
AG
AG
AG
AG
AK
AK
AH
AL
AG
AG
AG
AG
AG
P
R
AK
I
X
Z
AK
AK
AK
W
AH
AL
AG
AG
AG
AG
AG
AG
O

Part 2

Consider the following code:

public class StatefulPuzzle {
    private int x = 0;

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

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

        if (x < 2) {
            onClick(() -> {
                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
Bye!
x=2

Related puzzles: