本文介绍了Kotlin fun()vs 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.

如果不这样做,则返回类型推断的功能类似于正常函数,而不是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:

  • 没有隐式it参数,也没有解构.

  • There is no implicit it parameter, or destructuring.

    您的特定情况将是等效的.

    Your specific cases will be equivalent, yes.

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

  • 08-22 12:55