最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - How is a lambda invoked here without the need of a function parameter? - Stack Overflow

programmeradmin9浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论