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.

4
  • It seems same to me, just like how A.() -> B is same as (A) -> B in bytecode (both are KFunction1<A, B>) but inside syntax is different A.() -> B lets you have this as receiver while (A) -> B lets you have variable of any name. Similarly (String) -> String can be assigned to both of them, i.e. fun one is also an implementation of KFunction1<String, String>. Commented Jul 2, 2020 at 5:25
  • See also: stackoverflow.com/questions/58004914/…, stackoverflow.com/questions/43166375/… Commented Jul 2, 2020 at 7:56
  • 1
    Does this answer your question? Kotlin fun() vs lambda is there difference? Commented Jul 2, 2020 at 14:00
  • @KelvinM did my answer resolve your question? If so please accept the answer :) Commented Jul 2, 2020 at 20:23

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

I think lambda's return type can be specified too, like val toUpper: (String) -> String { }
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.
1

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.