kotlin - Kotlin-在重复功能中使用 Action 参数

标签 kotlin

我知道如何将时间作为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/

相关文章:

kotlin - "Leaking ' 这个 ' in constructor"警告应该适用于 final类和开放类(class)吗?

Kotlin 扩展函数与成员函数?

Kotlin:使用索引从列表创建 map

Android:切换 fragment 后按钮 onClicklistener 不起作用

java - Android 中的 Consumer-rules.pro 和 proguard-rules.pro 有什么区别?

android - 初始化百度 map SDK时出现UnsatisfiedLinkError

generics - Kotlin 绑定(bind)类型参数扩展重载

kotlin - 覆盖 Kotlin 数据类的 getter

java - Android kotlin google play billing onPurchasesUpdated 不覆盖任何内容或从未使用过

java - 如何使用JGit查找提交距离?