在Kotlin中,如果要使用forEach的元素,可以使用it关键字.所以现在我想知道,如果我有一个forEach中的forEach,我该怎么办:

list.forEach {
    val parent = it
    it.forEach {
        // `it` now become the element of the parent.
    }
}

I think that defines a new variable only for the naming convention be so stupid. Have any other solution for this problem?

推荐答案

it is just a default param name inside of all single argument closures. You could specify param name by yourself:

collection.forEach { customName -> 
    ...
}

Kotlin相关问答推荐

在Kotlin中处理结果的高阶函数

Kotlin多平台(KMP)保存到文件不能在iOS上保存

可选的.在kotlin中不使用泛型参数

访问者闭包中的Kotlin序列yield 率

使用 Jetpack Compose 使用参数导航

按钮无法在 Android Studio 上打开新活动

Kotlin - 协程未按预期执行

在 Kotlin 中,为什么在 `+` 之前但在 `.` 之前没有换行符?

JetPack Compose:添加点击持续时间

Kotlin 编译器在构造函数中报告未使用的表达式,以便构建器采用 vararg lambda

如果不为空,则为 builder 设置一个值 - Kotlin

如何从kotlin中的ArrayList中删除所有元素

Kotlin 中多个 init 块的用例?

带有迭代器函数的 Kotlin 无限序列

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

Kotlin:如何从另一个类访问字段?

Java中lazy的Kotlin类似功能是什么?

在 sharedPref.getString 中有一个默认值有什么意义?

如何将 CameraView 与 Jetpack Compose 一起使用?

内联 onFocusChange kotlin