Learn
Loops
Labeled Jump Expressions

“How would we use jump expressions inside nested loops?” Good question! The answer is labeled jump expressions. By adding a label to the outer loop of nested loops, we can execute a jump expression from the inner loop and have it act on the labeled outer loop.

First we need to give a name to our label. In the following example we choose the name rps. The outer loop is marked using our label rps followed by the @ symbol:

val game = listOf("Rock", "Paper", "Scissor") rps@ for (p1 in game) { for (p2 in game) { if (p1 == "Paper") { break@rps } println("$p1 vs. $p2") } }

The inner loop has an if expression that contains a break expression with @rps appended. When the condition, p1 == "Paper" is true, [email protected] executes and exits the outer loop:

Rock vs. Rock Rock vs. Paper Rock vs. Scissor

Now let’s look at what happens in our example when we change the break expression to a continue:

val game = listOf("Rock", "Paper", "Scissor") rps@ for (p1 in game) { for (p2 in game) { if (p1 == "Paper") { continue@rps } println("$p1 vs. $p2") } }

What we see now is the outer loop skips an iteration when p1 == "Paper" but resumes with the final iteration when p1 is equal to “Scissor”:

Rock vs. Rock Rock vs. Paper Rock vs. Scissor Scissor vs. Rock Scissor vs. Paper Scissor vs. Scissor

Labeled jump expressions give us more control over nested loops to help us achieve the desired behavior from our code. Using them can be tricky, but once understood they can be very powerful.

Instructions

1.

Recall the 6x6 grid with “A1” to “F6”” cells from the previous exercise. We’ll take a closer look at how we can manipulate the structure and output of this grid using labeled jump expressions.

First, add a label grid to the outer loop.

2.

Add an if expression inside the inner loop, before the print("$j$i ") statement. Have the condition test if the inner loop variable is equal to 'C'.

3.

Inside the if expression add a continue expression that jumps to the grid label.

Once you run the code you should see a single line of output. The outer loop numbers go from 1 through 6, but the inner loop letters only go up through 'B'.

It is important to note that the println() statement at the end of the outer loop is also skipped. The result is only one row is printed. This shows that a labeled continue will skip any code proceeding it in the inner loop and at the end of the outer loop.

Folder Icon

Take this course for free

Already have an account?