在重复函数中的索引(Kotlin)

huangapple go评论55阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月19日 15:20:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定