gpt4 book ai didi

kotlin - Kotlin Lambda语法

转载 作者:行者123 更新时间:2023-12-02 12:41:00 24 4
gpt4 key购买 nike

在下面的代码中,第二个添加有什么问题?

val lambdas  = mutableListOf<()->Unit>()
lambdas.add{println("a")} // this compiles fine
lambdas.add{()->println("b")} //why can't I do this?


error: expecting a name
lambdas.add{{()->println("b")}}

最佳答案

您无法以尝试的方式声明lambda

val right: () -> Int = { 1 } // Convenient way to declare a lambda without parameters
val alsoRight: () -> Int = { -> 1 } // The right way to explicitly declare a lambda without parameters
val wrong: () -> Int = { () -> 1 } // The wrong way to declare a lambda without parameters

该行应如下所示:
lambdas.add { -> println("b") }

关于kotlin - Kotlin Lambda语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60462110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com