每个回调都应返回创建它的那轮索引。请找出错误。 fun callbacks (): List < () -> Int > {
val result = mutableListOf < () -> Int > ()
var index = 0
while (index < 3 ) {
result += { index }
index ++
}
return result
}
fun main () {
println ( callbacks (). map { callback -> callback () })
}
查看答案
上一道练习 审查生成的事件注册表 审查AI代码
问问你的AI 让你的AI把这段代码改成引导式找错练习。
Claude ChatGPT 复制提示词 I am reading "每个回调都应返回创建它的那轮索引。请找出错误。" on CodeWiki (https://codewiki.com/zh/practice/spotbug/kotlin/lambdas/spotbug-loop-capture/).
Context (verbatim from the page):
"""
fun callbacks(): List<() -> Int> {
val result = mutableListOf<() -> Int>()
var index = 0
while (index < 3) {
result += { index }
index++
}
return result
}
fun main() {
println(callbacks().map { callback -> callback() })
}
"""
Introduce three subtle bugs into the example above and let me find them. Reveal each answer only after I have guessed.
Answer in 中文. Keep code examples in kotlin. Where you are unsure, say so.