3

This question is about fun() vs a lambda block definitions and scopes.
i have tried define the expressions in two ways. Here is what i have tried:

  val myFunction = fun(){
    println("i am in a function")
    }

//but i also tried doing this:

    val myFunction = {
    println("i am in a lambda")
    }

my problem is i do not know if they are equivalent and same thing ?

2
  • I believe return inside the body behaves differently. Like, in the first case, it'll be a return from myFunction, while in the second 1) in your current code you can't use return 2) As an argument to functions accepting lambdas it'll be a return from outer function. Also I suspect that first case disables inlining when passed as an argument. Commented Sep 19, 2019 at 6:31
  • 1
    @dyuhka please do not speculate. You can use links (for example to the language reference) to provide prove for your points. Commented Sep 19, 2019 at 6:46

2 Answers 2

7

The differences are best described in https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions:

  1. Anonymous functions allow you to specify return type, lambdas don't.

  2. If you don't, return type inference works like for normal functions, and not like for lambdas.

  3. As @dyukha said, the meaning of return is different:

    A return statement without a label always returns from the function declared with the fun keyword. This means that a return inside a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return from the anonymous function itself.

  4. There is no implicit it parameter, or destructuring.

Your specific cases will be equivalent, yes.

Sign up to request clarification or add additional context in comments.

2 Comments

Of course you can make lambda functions with return types. For example: val myVariable: (Int, String) -> String = { a: Int, b: String -> "$a + $b" }
In that case you don't specify the return type as a part of the lambda, but as the type of the variable you assigned it to. Doesn't help if the lambda is a part of a bigger expression.
1

See the reference: https://kotlinlang.org/docs/reference/lambdas.html

There are several ways to obtain an instance of a function type:

Using a code block within a function literal, in one of the forms:

  • a lambda expression: { a, b -> a + b },
  • an anonymous function: fun(s: String): Int { return s.toIntOrNull() ?: 0 }

Both give you a function object which can be used interchangeably

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.