3

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.

Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49
Kelvin M
  • 67
  • 5

3 Answers3

3

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.
jingx
  • 3,698
  • 3
  • 24
  • 40
  • I think lambda's return type can be specified too, like val toUpper: (String) -> String { } – Kelvin M Jul 02 '20 at 06:57
  • Kelvin M, that's not specifying the type of the lambda; it's specifying the type of variable you're assigning it to. In your example the effect is the same — but it's not if the lambda is used as a function parameter or in a more complex expression. – gidds Jul 02 '20 at 07:27
0

This website states: "Lambdas Expressions are essentially anonymous functions that we can treat as values – we can, for example, pass them as arguments to methods, return them, or do any other thing we could do with a normal object." (link)

So the answer is no, there isn't a difference between the two, they are interchangeable. Both of the codes you show above, will in the end return the same value to that variable

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52
0

Besides the differences pointed by @jingx, you can not local return from a lambda that is not inlined.

So, the next snippet will not compile unless you add inline to the extension() function, thus, instructing the compiler to copy the function's content whenever it is referenced:

fun doSomethingWithLambda(){
    10.extension{
        if(it == 10)
            return//compiler error
    }
    println("hello")
}

fun Int.extension(f: (Int)->Unit){
    f(this)
}
Raymond Arteaga
  • 4,355
  • 19
  • 35