Kotlin break
In Kotlin, the break
keyword is used to terminate the execution of a loop or a when expression early. When a break
statement is encountered inside a loop or a when expression, the program immediately exits the loop or the when expression and continues executing the next statement after the loop or the when expression.
Here's an example that demonstrates the use of the break
statement in Kotlin:
fun main() { val numbers = arrayOf(1, 2, 3, 4, 5) for (number in numbers) { if (number == 3) { break } println(number) } println("Done") }
In this example, the program creates an array of numbers, and then uses a for
loop to iterate over the array. Inside the loop, the program checks if the current number is equal to 3, and if it is, the program uses a break
statement to exit the loop early. After the loop, the program prints the string "Done" to the console. The output of the program is as follows:
1 2 Done
As you can see, the loop only iterated over the first two numbers in the array because the break
statement caused the loop to terminate early when it encountered the number 3.
You can also use a break
statement inside a when expression to terminate the execution of the expression early. Here's an example:
fun main() { val number = 3 val result = when (number) { 1 -> "One" 2 -> "Two" 3 -> { println("Found the number!") break } 4 -> "Four" else -> "Other" } println(result) }
In this example, the program uses a when expression to determine the value of the variable result
based on the value of the variable number
. Inside the when expression, the program checks if the value of number
is equal to 3, and if it is, the program uses a break
statement to terminate the execution of the when expression early. The output of the program is as follows:
Found the number!
As you can see, the break
statement caused the program to exit the when expression before it could finish executing. The value of result
is not set because the program did not reach the end of the when expression.