Home » Kotlin Return and Jump

Kotlin Return and Jump

by Online Tutorials Library

Kotlin Return and Jump

There are three jump expressions in Kotlin. These jump expressions are used for control the flow of program execution. These jump structures are:

  • break
  • continue
  • return

Break Expression

A break expression is used for terminate the nearest enclosing loop. It is almost used with if-else condition.

For example:

In the above example, for loop terminates its loop when if condition execute break expression.

Kotlin break example:

Output:

1  2  

In the above example, when the value of i became equal to 3 and satisfy the if condition(i==3) than the break expression execute and terminate for loop.

Kotlin Labeled break Expression

Labeled is the form of identifier followed by the @ sign, for example [email protected], [email protected]. To make an expression as label, we just put a label in front of expression.

Kotlin labeled break expression is used to terminate the specific loop. This is done by using break expression with @ sign followed by label name ([email protected]).

Kotlin labeled break example

Output:

i = 1 and j = 1  i = 1 and j = 2  i = 1 and j = 3  i = 2 and j = 1  

In the above example, when the value of i became 2 and satisfy the if condition which execute break expression followed by labeled name. The break expression followed by labeled name terminates the body of label identifier.

You may also like