英文:
Index in the repeat function(Kotlin)
问题
import kotlin.random.Random
fun main() {
var maximumDiscountValue = 0
repeat(3) { index ->
val discount = Random.nextInt(10)
println("Attempt ${index+1}: $discount")
if (discount > maximumDiscountValue) {
maximumDiscountValue = discount
}
}
println(maximumDiscountValue)
}
val number = 3
var output = 2
repeat(5) { index ->
output += (index * number)
}
println(output)
我不理解这里的“index”是做什么的。如果有人知道,我会很高兴知道。
英文:
I've been learning Kotlin lately and I came across something I can't understand.
import kotlin.random.Random
fun main() {
var maximumDiscountValue = 0
repeat(3) { index ->
val discount = Random.nextInt(10)
println("Attempt ${index+1}: $discount")
if (discount > maximumDiscountValue) {
maximumDiscountValue = discount
}
}
println(maximumDiscountValue)
}
val number = 3
var output = 2
repeat(5) { index ->
output += (index * number)
}
println(output)
I don't understand what "index" does in there. If someone knows what, I'll be glad to know.
答案1
得分: 1
The repeat
function specifies a number of times (3 and 5 in your case) a specific lambda function has to be executed. Index is a zero-based number that will be incremented during each execution.
In your first repeat
repeat(5) {
... your index will be 0, 1, 2, 3 and 4
}
Here the source code of the repeat function
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
contract { callsInPlace(action) }
for (index in 0 until times) {
action(index)
}
}
英文:
The repeat
function specifies a number of times (3 and 5 in your case) a specific lambada function has to be executed. Index is a zero-based number that will be incremented during each execution.
In your first repeat
repeat(5) {
... your index will be 0, 1, 2, 3 and 4
}
Here the source code of the repeat function
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
contract { callsInPlace(action) }
for (index in 0 until times) {
action(index)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论