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 badges1 Answer
Reset to default 1This 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
版权声明:本文标题:kotlin - How is a lambda invoked here without the need of a function parameter? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744105549a2591048.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论