Kotlin fun()vs lambda有区别吗? [英] Kotlin fun() vs lambda is there difference?
问题描述
这个问题是关于fun()与lambda块的定义和范围.
我试过用两种方式定义表达式.这是我尝试过的:
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 ?
推荐答案
最好在 https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions :
-
匿名函数使您可以指定返回类型,而lambda则不能.
Anonymous functions allow you to specify return type, lambdas don't.
如果不这样做,则返回类型推断的功能类似于正常函数,而不是lambda.
If you don't, return type inference works like for normal functions, and not like for lambdas.
正如@dyukha所说,return
的含义不同:
As @dyukha said, the meaning of return
is different:
没有标签的return语句总是从用fun关键字声明的函数中返回.这意味着lambda表达式内部的返回将从封闭函数返回,而匿名函数内部的返回将从匿名函数本身返回.
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.
没有隐式it
参数,也没有解构.
There is no implicit it
parameter, or destructuring.
您的特定情况将是等效的.
Your specific cases will be equivalent, yes.
这篇关于Kotlin fun()vs lambda有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!