Kotlin中repeat函数action参数用法及(Int)->Unit含义咨询
(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 typeInt. Forrepeat, 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.Unitis Kotlin’s version of Java’svoid—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:
- The number of times to repeat (
times: Int) - 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:
1. Trailing Lambda (Recommended)
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

