Kotlin-在重复功能中使用动作参数 [英] Kotlin - use action parameter in repeat function

查看:73
本文介绍了Kotlin-在重复功能中使用动作参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何将时间作为repeat函数的第一个参数:

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

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

但是我检查了Kotlin文档,它显示还有另一个参数action可以使用(请参阅科林文档):

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)

我尝试了这段代码,但失败,并出现错误 Expecting')':

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.")
}

我知道我遇到了语法错误.所以我的问题是:什么是(Int) -> Unit以及如何正确使用action参数?

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

推荐答案

什么是(Int)->单位以及如何正确使用action参数?

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

(Int) -> Unit描述了一个采用Int并返回Unit(无效)的函数.为了按原样调用它,您可以这样做:

(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()})

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")
}

这篇关于Kotlin-在重复功能中使用动作参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆