admin管理员组

文章数量:1394735

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?

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?

Share Improve this question asked Mar 27 at 7:59 Ken KiarieKen Kiarie 1411 gold badge1 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.

本文标签: kotlinHow is a lambda invoked here without the need of a function parameterStack Overflow