What does "return@" mean in Kotlin?


return@ is a statement in Kotlin which helps the developers to return a function to the called function. In simple words, return@ can return any value, anonymous function, simple inline function, or a lambda function.

Example – return in Kotlin

fun main(args: Array<String>) {
   val s = message()
   println("Message = $s")
}
fun message():String{
   return "Hello Kotlin! This is a returned message."
}

Output

It will produce the following output −

Message = Hello Kotlin! This is a returned message.

Example – Kotlin Labeled return

Now "return@" helps to control the flow to a specific level inside the code. In Kotlin terminology, it is known as "Labeled return" often it is denoted using return@label. Let's take an example to demonstrate how it works.

fun ArraySum(intArray: List<Int>) {
   intArray.forEach {

      // return to the forEach block
      // whenever the condition is met
      if (it == 30) return@forEach
      print(it)
   }
   print("---Control skipped for the value of 30")
}
fun main(args: Array<String>) {
   ArraySum(listOf(1,2,3,4,5,6,30,40))
}

Output

It will generate the following output −

12345640---Control skipped for the value of 30

Updated on: 16-Mar-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements