Chapter summary
Repeating instructions without having to write them over and over is very useful, and we achieve that using different forms of recursion and loops:
- Jumping to a label: a somewhat “low-level” way to return to a specific point in the code using continue :label value. We use it inside a labeled switch to repeat a block with new data.
- Recursion: one of the favorites among functional programmers. It means the function calls itself, but with modified parameters to avoid infinite recursion and prevent crashing the program. If you’re going to use it, tail recursion is the better choice.
- While: executes a block of code as long as a condition is true. It can include a label and an increment instruction, use break and continue, and also have an else block that runs either if the loop was never entered or after it ends (as long as it wasn’t exited with break).
- For: the ideal loop when we want to iterate over arrays, slices, and ranges. It lets us traverse them even in parallel, get the index automatically with 0.., and we can also use break and continue to exit or skip as needed.
- Continue and Break: continue jumps to the start of the loop, skipping the rest of the block, and break interrupts the loop. We use them to skip invalid elements, stop iterating, or jump to a label. They let us (complicate) control the flow of any iteration.
- Optional values in loops and orelse: We can capture optionals (which may be null) and act only on valid ones, or provide default values with orelse when we encounter a null.