Kotlin - use action parameter in repeat function

*爱你&永不变心* 提交于 2020-07-22 06:14:11

问题


I know how to pass times as the first parameter of repeat function:

repeat(3) {
  println("This will print 3 times")
}

But I checked Kotlin documentation, it shows there's another parameter action to use(see kotlin doc):

inline fun repeat(times: Int, action: (Int) -> Unit)

I tried this code but failed with the error Expecting ')':

repeat(3, 2 -> anotherFun()) {
    println("This will show 2 times?")
}

fun anotherFun() {
    println("head into the 2nd time and print this out.")
}

I know I have got the syntax error. so my question is: what is (Int) -> Unit and how to use the action parameter properly?


回答1:


what is (Int) -> Unit and how to use the action parameter properly?

(Int) -> Unit describes a function that takes an Int and returns Unit (void). In order to call it as-is, you can do it like this:

repeat(3, {anotherFunction()})

Or

repeat(3) {
    anotherFunction()
}

However, the number of iterations that will happen is not available, but you could define your own by borrowing from the one in the standard library...

public inline fun repeat(times: Int, action: (Int, Int) -> Unit) {
    for (index in 0 until times) {
        action(times, index)
    }
}

And then you can use it like this:

repeat(3) { times, i ->
    println("Called $i/$times")
}



回答2:


I know I have got the syntax error. so my question is: what is (Int) -> Unit and how to use the action parameter properly?

repeat(3) {
    println("This will print 3 times, $it cycle number")
}



回答3:


If you need the overall number of iterations within the lambda, you can declare a variable (val) outside of it beforehand as well:

val i = 3
repeat(i) {
    println("iteration $it of $i")
}


来源:https://stackoverflow.com/questions/50341113/kotlin-use-action-parameter-in-repeat-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!