https://kotlinlang.org logo
#announcements
Title
# announcements
m

Miguel Vargas

08/29/2019, 1:04 AM
As I'm trying to wrap my head around all the coroutine concepts one thing that is tripping me up are
suspend
functions. The keyword is not very well documented but it does say that they can only be used from a coroutine. But then I ran into sequence's
yield()
which is a suspend function that it is called from a SequenceScope which is not a coroutine scope. As far as I know Sequences have been in Kotlin 1.0 so it precedes coroutines? I guess I'm trying to get a more basic understanding of suspend functions.
c

Casey Brooks

08/29/2019, 1:28 AM
The general idea is that a function marked
suspend
can only be called from other functions which are marked
suspend
. However, lambdas can also be marked suspend, and this is the magic that makes it all work. Certain non-
suspend
functions create the root scope for coroutines to live within, and these functions expose that scope through a suspending lambda, which is part of the function definition. For Sequences, the
sequence { }
call needs a block of type
suspend SequenceScope<T>.() -> Unit
(notice it's marked
suspend
). The Receiver is
SequenceScope
, and
yield()
is a function on
SequenceScope
, but it is also marked as
suspend
, which means it can only be called from within another
suspending
function. Because the lambda of
sequence
is a suspending function, you can call
yield()
within that lambda
👍 1
2 Views