簡體   English   中英

如何在Kotlin的forEach上引用外部

[英]How to refer to outer this on forEach in Kotlin

我有以下情況

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每個項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM