Returns, Jumps and Labels in Kotlin
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:
These can be a part of the large expression as Kotlin say. So, let’s start with “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,
Another use of return
So, that’s how the return statement work.
2. Jumps & labels
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.
We can also optimize the above code or reduce the line of code as well, using 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.
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.
That’s all about return, jump, and labels.