Returns, Jumps and Labels in Kotlin
Last Updated :
10 Nov, 2021
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is an object-oriented language, and a “better language” than Java, but still be fully interoperable with Java code. As the Kotlin says: Kotlin has three structural jump expressions as follow:
- return
- break
- continue
These can be a part of the large expression as Kotlin say. So, let’s start with “return”.
1. return
It’s a statement that generally we use in functions during declaration for returning the values after execution of a function. By default it returns from the nearest enclosing function or anonymous function. Let’s take an example,
Example:
Kotlin
fun add(a:Int,b:Int) : Int {
val ans = a + b
return ans
}
fun main(args: Array<String>) {
val first: Int = 10
val second: Int = 20
val sum = add(first,second)
println( "The sum is: $sum" )
}
|
Another use of return
Kotlin
fun GfG() {
listOf( 1 , 2 , 3 , 4 , 5 ).forEach {
if (it == 3 ) return
print(it)
}
println( "this point is unreachable" )
}
|
So, that’s how the return statement work.
2. Jumps & labels
2.1. break
A break statement is used to terminate the flow of a loop. but only terminates the nearest enclosing loop i.e. if you are having two nested for-loops and the break statement is present in the inner for-loop then the inner for-loop will be terminated first and after that, if another break is added then the outer for-loop will also be terminated.
Example:
Kotlin
fun main(args : Array<String>){
for (ch in 'A' .. 'C' ){
for (n in 1 .. 4 ){
println( "processing..." )
if (n == 2 )
break
}
if (ch == B)
break
}
}
|
We can also optimize the above code or reduce the line of code as well, using labels.
2.2. labels
Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, such as name@ or xyz@. To label an expression, just add a label in front of it.
Example:
Kotlin
fun main(args : Array<String>){
Outerloop@ for (ch in 'A' .. 'C' ){
for (n in 1 .. 4 ){
println( "processing..." )
if (n == 2 )
break @Outerloop
}
}
}
|
2.3. continue
It is the same as the break statement but the only difference is, the break statement terminates the whole iteration of a loop whereas continuing skips the current iteration and we can use labels here as well.
Example:
Kotlin
fun main(args: Array<String>) {
outerloop@ for (i in 1 .. 5 ) {
for (j in 1 .. 4 ) {
if (i == 3 || j == 2 )
continue @outerloop
println( "Happy Diwali!" )
}
}
}
|
That’s all about return, jump, and labels.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...