[英]How to refer to outer this on forEach in Kotlin
我有以下情況
someThing.forEach{
someWidget.setOnClickListener{
//it is an View
//I need foreach it of someObject
}
}
我讀了這個答案,但是沒有用
問題是您在這里沒有處理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
每個項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.