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

Time:11-23

How can I create my own lambda expression that is similar to forEach (kotlin-stdlib)?

Scenario:

For each object of a list, I wrap it in another object and call a wrapper method like below:

class Action {
  fun runA() {
    objects.forEach { obj ->
      val wrapper = Wrapper(obj)
      wrapper.runA()
    }
  }
}

Problem:

I want to create runB without duplicating code. How can I do this elegantly in Kotlin?

I cannot pass a parameter method like below, as the method I want to call belongs to an instance that I haven't created yet.

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

Ideally, I'd want something like this:

class Action {
// ...
fun runA() {
  runMethod { wrapper ->
    wrapper->runA()
  }
}

fun runB() {
  runMethod { wrapper ->
    wrapper->runB()
  }
}
}

CodePudding user response:

If I understand your problem correctly, you can add a receiver to the lambda passed to the runMethod() function. Thia way Wrapper becomes this inside the passed 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()
    }
}
  • Related