我想知道是否有等同于 Swift's @autoclosure
feature 的东西
本质上,我希望能够在一个函数或构造函数/初始化器中创建一个参数,它可以接受另一个接受参数的函数,并执行它:
class Step(handler: () -> Unit) {
init {
handler()
}
}
Step(aFunctionThatTakesParameters(parameter: String)) // <- Is there a way to get something like this working?
作为引用,Swift 中的等效代码如下所示:
struct Step {
init(_ handler: @autoclosure () -> Void) {
handler()
}
}
Step(aFunctionThatTakesParameters(parameter: ""))
最佳答案
我在链接中打开了自动闭包的 Swift 文档: https://docs.swift.org/swift-book/LanguageGuide/Closures.html#ID543
引用这段代码:
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
// Prints "5"
let customerProvider = { customersInLine.remove(at: 0) }
print(customersInLine.count)
// Prints "5"
print("Now serving \(customerProvider())!")
// Prints "Now serving Chris!"
print(customersInLine.count)
// Prints "4"
然后我编写了以下代码以将 Swift 翻译成 Kotlin:
val customersInLine = mutableListOf("Chris", "Alex", "Ema", "Barry", "Daniella")
println(customersInLine.size)
// Prints "5"
val customerProvider = { customersInLine.removeAt(0) }
println(customersInLine.size)
// Prints "5"
println("Now serving ${customerProvider()}!")
// Prints "Now serving Chris!"
println(customersInLine.size)
// Prints "4"
虽然这似乎没有提供您正在寻找的预期输出,但您可以按照...做更多的事情
class Step (handler: () -> Unit) {
init {
handler()
}
}
fun myParamFunction(a: String, b: String) {
a + b
}
Step {
myParamFunction("Hello ", "there")
}
在这种情况下,Kotlin 能做的最好的事情就是采用一个纯 lambda 函数,并在内部调用一个已给定要调用的参数的函数。
关于Kotlin 等同于 Swift 的 `@autoclosure`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54182352/