如何在Kotlin的forEach上引用外部this



我有以下情况

someThing.forEach{
someWidget.setOnClickListener{
//it is an View
//I need foreach it of someObject
}
}

我读了这个答案,但它不起作用

kotlin如何在多层应用函数中引用外部范围

问题是您在这里没有处理this

forEach有一个参数,为了简单起见,您可以不使用它,只使用it。不使用它与使用_ ->相同。。。你只要丢弃它。

因此,您的示例使用命名的lambda参数编写:

someThing.forEach{ some -> // 'it' was available here too, but will not be accessible from within the next setOnClickListener...
someWidget.setOnClickListener{
// some contains one of the someThings now and 'it' is still your View
}
}

您可以在forEach中命名变量。

things.forEach { thing ->
someWidget.setOnClickListener {
thing.doSomething()
}
}

我想你的意思是这样的:

someThing.forEach{ x->
someWidget.setOnClickListener{
//use x
//I need foreach it of someObject
}
}

只需使用另一个名称,如x,就不必使用it
这里有一个例子:

val a = mutableListOf<Int>(1, 3)
val b = mutableListOf<Int>(2, 4)
a.forEach { x ->
b.forEach {
println("" + x + " " + it)
}
}

这里x是列表a中的每个项目
it是列表b中的每个项

最新更新