I'm provided a class Foo which does some work():
open class Foo() {
fun work(x: T) {
// Effects taking place here
}
}
And I am also provided (but by someone else) a method useJob() which consumes an object of interface type Bar having a single method doJob().
fun useJob(bar: Bar)
interface Bar {
fun doJob(x: T)
}
It turns out Foo.work() does the job expected by useJob(). However, in order to have useJob() calling work(), I need to write something like that:
useJob(object : Foo(), Bar { fun doJob(x: T) { work(x) } })
Is there any way to use a lambda instead of this blob?
EDIT: @jrtapsell comment made me realize Foo is actually open.
If
Barwere defined in Java, you could writeor
to avoid constructing
Foo()every time in caseuseJobcalls its argument multiple times.But
Without moving
Barto Java, I'd go with joecks' solution or define an overload ofuseJob(possibly as extension method). Which is better depends on how many methods likeuseJobyou have and how many uses for each.