android - 不明白这个 Lambda 函数是如何工作的

标签 android kotlin

我是 Kotlin 的新手,几天前才了解 lambda 函数。

所以,我的理解是:

假设我有一个将 lambda 函数作为参数的函数:

class XX
{
    fun addTowNumbers(a:Int , b:Int , action: (Int,Int) -> Int)
    {
        val result = action(a,b)
            println(result)
    }
}

并这样调用它:

fun main(args: Array<String>)
{
    val x = XX();
    val myLambda: (Int, Int) -> Int = {x,y ->  x+y}

    x.addTowNumbers(2,5, myLambda)
}

但是今天看到了一个新的方法,就是下面。

lambda 函数:

 val sum: (Int, Int) -> Int = { x, y -> x + y }

使用 lambda 函数作为参数的高级函数:

 fun applyOp(x: Int, y: Int, op: (Int, Int) -> Int): Int = op(x, y)

并这样调用它:

 applyOp(2, 3, sum)

所以,现在我对高级功能感到困惑。参数中怎么会有2个冒号

op: (Int, Int) -> Int): Int = op(x, y)

另外,为什么会有等号?

总的 lambda 参数在做什么?

最佳答案

这是一个带有表达式主体的函数:

fun applyOp(x: Int, y: Int, op: (Int, Int) -> Int): Int = op(x, y)

您可能习惯于看到带有 block 体的函数:

fun applyOp(x: Int, y: Int, op: (Int, Int) -> Int): Int {
    return op(x, y)
}

这两个是等价的;表达式体只是一种更简洁的写法。

同样,这两个函数是相同的:

fun helloWorld(): String {
    return "Hello World!"
}

fun helloWorld(): String = "Hello World!"

如果您使用表达式主体,您甚至可以不指定函数类型:

fun helloWorld() = "Hello World!"

关于android - 不明白这个 Lambda 函数是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58528461/

相关文章:

android - Dagger 2 没有注入(inject) sharedPreference

android - 使用 Espresso 进行测试时,如何在 Android 上的 NavigationView 中单击菜单项?

android - 使用 Kotlin 1.6.0 的 proguard/R8 删除了数据类元数据

android - Kotlin IllegalStateException : Resource not found in classpath: kotlin/. kotlin_string_table

android - 在android q中如何获取android文档目录的路径?

spring - 如何在 Kotlin 中使用@ConfigurationProperties

android - 错误 libGL.so : cannot open shared object file using Android emulator

android - FirebaseMessagingService 是否在设备重启后仍然存在?

javascript - 从 Android 调用 JavaScript

android - 在 DDMS 设置默认模拟位置数据