Search code examples
kotlinlambdafunctional-interface

Kotlin Return function as fun interface


Functional interfaces work well when you want to inject a function as an interface, example:

fun interface MakeCoffee {
    operator fun invoke()
}

class CoffeeManager(private val makeCoffee: MakeCoffee) {...}

fun provideCoffeeManager(): CoffeeManager = CoffeeManager {  }

However if I try to return a function when the return type is a fun interface like this:

fun provideMakeCoffee(): MakeCoffee = {}

it will fail for a mismatch KFunction0<Unit> vs MakeCoffee.

Is there any workaround?


Solution

  • I found the solution to the problem in the end. @Tenfour04 answer works but it doesn't answer the question of "how to return a function as fun interface".

    The example provided was very simple and maybe that's why the question was a bit misleading, but imagine you have the following case:

    fun interface MakeCoffee {
        operator fun invoke(sugarAmount: Double, milkAmount: Double, coffeeAmount: Double)
    }
    
    //function you already have
    fun doCoffee(sugarAmount: Double, milkAmount: Double, coffeeAmount: Double) { ... }
    

    How do you return your doCoffee as MakeCoffee?

    Solution

    fun provideMakeCoffee(): MakeCoffee = MakeCoffee(::doCoffee)