Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading