You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中repeat函数action参数用法及(Int)->Unit含义咨询

Understanding (Int) -> Unit and Correct Usage of repeat's action Parameter

Hey there! Let's clear up your confusion and fix that error in your code.

What does (Int) -> Unit mean?

This is a function type in Kotlin. Let's break it down simply:

  • (Int): The function takes one parameter of type Int. For repeat, this parameter is the loop index (starting at 0, not 1!) that gets passed to the function every time it runs.
  • -> Unit: The function doesn’t return any meaningful value. Unit is Kotlin’s version of Java’s void—it tells you the function performs an action but sends back no data.

Why was your code throwing an error?

Your code had a syntax misstep in how you passed the action parameter. The repeat function only accepts two arguments:

  1. The number of times to repeat (times: Int)
  2. The function to execute each cycle (action: (Int) -> Unit)

This line was invalid:

repeat(3, 2 -> anotherFun()) { println("This will show 2 times?") }
  • You tried to pass three arguments instead of two
  • 2 -> anotherFun() isn’t a valid way to define the action function—you can’t hardcode a specific index directly in the argument list like that

Correct Usage of repeat's action Parameter

There are two common ways to use the action parameter, with the trailing lambda syntax being the most natural in Kotlin:

When the last parameter of a function is a function type, you can move the lambda outside the parentheses for cleaner, more readable code:

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

fun main() {
    repeat(3) { index ->
        // Remember: index starts at 0, so the 2nd iteration is index = 1
        if (index == 1) {
            anotherFun()
        } else {
            println("This will print on the 1st and 3rd iterations")
        }
    }
}

2. Lambda Inside Parentheses

You can also pass the lambda directly inside the parentheses, though this is less common for readability:

repeat(3, { index ->
    if (index == 1) {
        anotherFun()
    } else {
        println("This will print on the 1st and 3rd iterations")
    }
})

Example Using the Index Parameter

If you want to use the loop index directly (e.g., to track which iteration you’re on), here’s a quick demo:

repeat(3) { count ->
    println("This is iteration ${count + 1} (index starts at 0)")
}

This will output:

This is iteration 1 (index starts at 0)
This is iteration 2 (index starts at 0)
This is iteration 3 (index starts at 0)

内容的提问来源于stack exchange,提问作者shisaq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:47:45