Skip to content

Instantly share code, notes, and snippets.

@ajaypro
Last active August 13, 2019 12:14
Show Gist options
  • Save ajaypro/91844427318bb71cf7afc75ece18a839 to your computer and use it in GitHub Desktop.
Save ajaypro/91844427318bb71cf7afc75ece18a839 to your computer and use it in GitHub Desktop.
Learn how to use unlabled and labled return from function and lambdas
Labledreturn from function
fun main(args: Array<String>) {
foo(listOf(1,0,3,4))
}
fun foo(ints: List<Int>) {
ints.forEach inner@ {
if (it == 0) return@inner
println(it)
}
println("Hii there")
}
When you run the program, you will get below output:
1
3
4
Hii there
Explanation: return@inner will cause the program to jump it’s control to label inner. In this program, we are checking each
time if the value inside forEach loop is 0 or not. If it is 0, control is being returned to label inner@.
labledReturn from lambda expression
If you want to return from lambda expression rather than nearest enclosing function, you will have to use labeled return statement. For example,
fun main(args: Array<String>) {
foo(listOf(1,2,0,4))
}
fun foo(ints: List<Int>) {
ints.forEach inner@ {
if (it == 0) return@inner
println(it)
}
println("Hi there")
}
Output:
1
2
4
Hi there
In the above example, when value if it will be 0, return@inner will cause the control of the program to return to label inner@.
Above example can be re-written using implicit labels. Such label has same name as the function to which the lambda is passed. So, above example using implicit label is
fun main(args: Array<String>) {
foo(listOf(1,2,0,4))
}
fun foo(ints: List<Int>) {
ints.forEach {
if (it == 0) return@forEach
println(it)
}
println("Hi there")
}
Output:
1
2
4
Hi there
How to use return in lambda expression in kotlin
When unlabeled return is used with lambda expression, it returns from nearest enclosing function. For example,
fun main(args: Array<String>) {
foo(listOf(1,2,0,4))
}
fun foo(ints: List<Int>) {
ints.forEach {
if (it == 0) return
println(it)
}
println("Hi there")
}
output : 1
2
In above example, return statements causes the control of the program to jump from that line to the caller of the function foo()
i.e. This is non-local return from inside lambda expression directly to the caller of the function foo().
Return use in function
Here, we will talk about use of return in function. return statement in function causes the control of the program to return from that function to the caller of the function. For example,
fun main(args: Array<String>) {
val product = multiply(3,5)
println("product = $product")
}
fun multiply(first: Int, second: Int) : Int {
return first * second;
}
output is :
product = 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment