
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Break and Continue in Foreach Loop in Kotlin
In Kotlin, we have three types of structural jump expressions: "break", "return", and "continue". In this article, we will see how break and continue work in Kotliln.
Break - This is a keyword that helps in terminating an iteration, once a given condition is met, while traversing through a collection.
Continue - This keyword helps to continue the iteration once a condition is fulfilled.
In Kotlin, we cannot explicitly use break and continue statements explicitly inside a forEach loop, but we can simulate the same action. In this example, we will see how to do it.
Example: Return at labels :: directly to the caller
In this example, we will see how to stop the execution in the current loop and move back the compiler execution to the caller function. This is the equivalent of break.
fun main(args: Array<String>) { myFun() println("Welcome to TutorialsPoint") } fun myFun() { listOf(1, 2, 3, 4, 5).forEach { // break this iteration when // the condition is satisfied and // jump back to the calling function if (it == 3) return println(it) } println("This line won't be executed." + "It will be directly jump out" + "to the calling function, i.e., main()") }
Output
Once we execute the above piece of code, it will terminate the execution of the function myFun() and return to the calling function, that is, main(), once the value of the iteration index to 3.
1 2 Welcome to TutorialsPoint
Example: Return at labels :: local return to the caller
In the above example, if we want to stop the loop execution only for a specific condition, then we can implement a local return to the caller. In this example, we will see how we can implement the same. This is the equivalent of "continue".
fun main(args: Array<String>) { myFun() println("Welcome to TutorialsPoint") } fun myFun() { listOf(1, 2, 3, 4, 5).forEach ca@{ // break this iteration when the condition // is satisfied and continue with the flow if (it == 3) return@ca println(it) } println("This line will be executed
" + "because we are locally returing
" + "the execution to the forEach block again") }
Output
It will generate the following output
1 2 4 5 This line will be executed because we are locally returning the execution to the forEach block again Welcome to TutorialsPoint