Kotlin fun() vs lambda is there difference?

偶尔善良 提交于 2021-01-29 03:09:05

问题


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 ?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/58004914/kotlin-fun-vs-lambda-is-there-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!