创建一个 returns 每个内部对象的 lambda(比如 forEach)

Create a lambda that returns each internal object (like forEach)

如何创建自己的类似于 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()
  }
}
}

如果我对您的问题的理解正确,您可以向传递给 runMethod() 函数的 lambda 添加一个接收器。这样 Wrapper 在传递的 lambda 中变为 this

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()
    }
}