我想知道是否有与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: ""))
答案 0 :(得分:0)
我在链接处打开了有关自动关闭的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函数,并在内部调用已被赋予要调用参数的函数。