Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any significant differences between lambda expressions & anonymous function in Kotlin?

Tags:

kotlin

Kotlin has these 2 features and I think there're no significant differences between these two regardless of :

  1. syntax
// lambda
val toUpper = { value: String -> 
   if (value.isEmpty()) "empty value"
   else value.toUpperCase()
}

// anonymous func
val toUpper = fun(value: String): String {
  if (value.isEmpty()) return "empty value"
  else return value.toUpperCase()
}
  1. flexibility to use return statement on anonymous function

I'm still digesting these features and hope you guys can help me pass through it. Thanks.

like image 845
Kelvin M Avatar asked Jun 22 '26 23:06

Kelvin M


1 Answers

Two differences according to Kotlin Reference:

  1. (I think the more significant one out of the two) An anonymous function is still a function, so returning from it behaves the same as returning from any function. Returning from a lambda, however, actually returns from the function enclosing the lambda.
  2. The return type of a lambda is inferred, while you can explicitly specify a return type for an anonymous function.
like image 124
jingx Avatar answered Jun 24 '26 15:06

jingx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!