Java Can Have Coroutines!

Like Lua has. Impossible? Not so! It can be done in JavaX.

For now, turning a function into a coroutine requires a bit of (straight-forward) source code transformation — but of course those transformations could later be automated too.

We can make working coroutines right now if we do the translation manually. [Working example!]

Example: A for loop

for (int i = 1; i <= 3; i++)
print("Counting to " + i + "!");

turns into this coroutine making expression:

_for(r { i = 1 }, func { i <= 3 }, r { i++ }, r {
print("Counting to " + i + "!");
})

It basically has a few more brackets; and you need to put the i variable in a suitable place (static or in an object, not local).

Then, voila: Your code can be run as a coroutine, which means, it can be run in small steps (via the doStep function) and interrupted at any time, thereby yielding time to other coroutines. A useful feature indeed, for example to parallelize multiple computations on a single processor.

You see: The impossible becomes possible with JavaX!

Next time, if you ask me to, we can cover how to use function calls in coroutines (including recursion!).