如何創建自己的類似于forEach(kotlin-stdlib)的 lambda 運算式?
設想:
對于串列的每個物件,我將它包裝在另一個物件中并呼叫如下包裝方法:
class Action {
fun runA() {
objects.forEach { obj ->
val wrapper = Wrapper(obj)
wrapper.runA()
}
}
}
問題:
我想在runB不重復代碼的情況下進行創建。我怎樣才能在 Kotlin 中優雅地做到這一點?
我不能傳遞像下面這樣的引數方法,因為我要呼叫的方法屬于我尚未創建的實體。
class Action {
fun runMethod(method: () -> Unit) {
objects.forEach { obj ->
val wrapper = Wrapper(obj)
method() // I want: wrapper.method(), but wrapper is created in the forEach lambda
}
}
fun runA() { ... }
fun runB() { ... }
}
理想情況下,我想要這樣的東西:
class Action {
// ...
fun runA() {
runMethod { wrapper ->
wrapper->runA()
}
}
fun runB() {
runMethod { wrapper ->
wrapper->runB()
}
}
}
uj5u.com熱心網友回復:
如果我正確理解您的問題,您可以向傳遞給runMethod()函式的 lambda 添加一個接收器。這種方式Wrapper變成this了傳遞的 lambda 內部:
fun main() {
runMethod { runA() }
runMethod { runB() }
// or:
runMethod(Wrapper::runA)
runMethod(Wrapper::runB)
}
fun runMethod(method: Wrapper.() -> Unit) {
objects.forEach { obj ->
val wrapper = Wrapper(obj)
wrapper.method()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363404.html
