我知道如何将时间作为repeat
函数的第一个参数:
repeat(3) {
println("This will print 3 times")
}
但是我检查了Kotlin文档,它显示还有另一个参数
action
可以使用(请参阅kotlin doc):inline fun repeat(times: Int, action: (Int) -> Unit)
我尝试了这段代码,但由于出现错误期望')'而失败:
repeat(3, 2 -> anotherFun()) {
println("This will show 2 times?")
}
fun anotherFun() {
println("head into the 2nd time and print this out.")
}
我知道我有语法错误。所以我的问题是:什么是
(Int) -> Unit
以及如何正确使用action参数?
最佳答案
what is (Int) -> Unit and how to use the action parameter properly?
(Int) -> Unit
描述了一个函数,该函数采用Int
并返回Unit
(无效)。为了按原样调用它,您可以这样操作:repeat(3, {anotherFunction()})
要么
repeat(3) {
anotherFunction()
}
但是,将无法进行的迭代次数是多少,但是您可以通过从标准库中的一次迭代中定义自己的迭代次数...
public inline fun repeat(times: Int, action: (Int, Int) -> Unit) {
for (index in 0 until times) {
action(times, index)
}
}
然后您可以像这样使用它:
repeat(3) { times, i ->
println("Called $i/$times")
}
关于kotlin - Kotlin-在重复功能中使用 Action 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341113/