kotlinkotlin-flowfunction-parameter

How is a lambda invoked here without the need of a function parameter?


Learning about flows and the interface definition is this:

interface Flow<out T>{
    suspend fun collect(collector: FlowCollector<T>)
}

collect has no function parameter yet I'm allowed to invoke a lambda upon calling the method on a Flow as such:

var letters = flow{
    emit("A")
    emit("B")
}
fun main() = runBlocking{
    letters.collect{
        println(it)
    }
}

How is this convention possible without the need of having a function parameter in collect's signature?


Solution

  • This works because the parameter FlowCollector is a SAM (Single Abstract Method) interface. Also, you can move the function body(lambda) out of the( ... ) . Further, as the SAM is the only parameter of the collect function, so it can be written in this way:

    theFlowObject.collect { 
        //the SAM implementation here
    }
    

    Hope it helps.