Search code examples
lambdakotlinobject-expression

Lambda in multiple type object expression


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.


Solution

  • If Bar were defined in Java, you could write

    useJob { Foo().work(x) }
    

    or

    val foo = Foo()
    useJob { foo.work(x) }
    

    to avoid constructing Foo() every time in case useJob calls its argument multiple times.

    But

    note that this feature works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.

    Without moving Bar to Java, I'd go with joecks' solution or define an overload of useJob (possibly as extension method). Which is better depends on how many methods like useJob you have and how many uses for each.