Kotlin Break, Return and Continue Statement
Expert-led Courses: Transform Your Career – Enroll Now
In Kotlin, return and jump statements play a crucial role in controlling the flow of execution within a program. These statements allow developers to exit or skip certain sections of code based on specific conditions. In this article, we will explore the concepts of break, continue, and return statements in Kotlin.
Break Statement in Kotlin
The break statement is used to terminate the execution of a loop, such as a for loop or a while loop, prematurely. It allows you to exit the loop even if the loop condition is not met. Let’s consider an example to illustrate its usage:
fun main() {
for (i in 1..10) {
if (i == 5) {
break
}
println(i)
}
}
Output:
2
3
4
Code Explanation
In the above code, the loop will terminate when `i` becomes 5 due to the `break` statement. As a result, only the numbers 1 to 4 will be printed.
Kotlin Continue Statement:
The continue statement is used to skip the rest of the code block within a loop iteration and move to the next iteration. It is commonly used to skip certain iterations based on specific conditions. Let’s see an example:
fun main() {
for (i in 1..5) {
if (i == 3) {
continue
}
println(i)
}
}
Output:
2
4
5
Code Explanation
In the above code, when `i` is equal to 3, the continue statement is encountered, and the loop skips printing that number. The loop continues with the next iteration, printing all other numbers.
Return Statement in Kotlin
The return statement is used to exit a function or a lambda expression and return a value. It can also be used to terminate the execution of a block of code in a larger scope. Here’s an example that demonstrates the usage of return:
fun sum(a: Int, b: Int): Int {
val total = a + b
return total
}
fun main() {
val result = sum(3, 5)
println("Sum: $result")
}
Output:
Code Explanation
In the above code, the sum() function takes two integers as parameters, calculates their sum, and returns the result using the return statement. The main() function then calls the sum() function and prints the returned value.
Conclusion:
In Kotlin, return and jump statements provide developers with powerful tools to control the flow of execution in their programs. The break statement allows premature termination of loops, the continue statement skips iterations, and the return statement exits functions or lambda expressions. Understanding and using these statements effectively can greatly enhance the flexibility and control of your Kotlin programs.
Happy Coding! 🙂
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

