Kotlin fun() 与 lambda 有区别吗? [英] Kotlin fun() vs lambda is there difference?

查看:26
本文介绍了Kotlin fun() 与 lambda 有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是关于 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:

  1. 匿名函数允许您指定返回类型,而 lambda 则不允许.

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

如果你不这样做,返回类型推断就像普通函数一样,而不像 lambdas.

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 表达式内的 return 将从封闭函数返回,而匿名函数内的 return 将从匿名函数本身返回.

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 参数或解构.

    你的具体情况是等价的,是的.

    Your specific cases will be equivalent, yes.

    这篇关于Kotlin fun() 与 lambda 有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆