https://kotlinlang.org logo
#coroutines
Title
# coroutines
i

iex

07/12/2020, 4:59 PM
Hi! How do I make this compile?
Copy code
private suspend fun myStruct(): MyStruct = MyStruct(1) {
    foo()
}

suspend fun foo() {}

private data class MyStruct(
    val a: Int,
    val callback: (() -> Unit)?
)
a

Adam Powell

07/12/2020, 5:06 PM
What would you like the behavior of a call to
myStruct()
to be?
s

streetsofboston

07/12/2020, 5:10 PM
foo
is a suspend fun. Your
callback
parameter must be declared suspend as well if passing it
foo
, or something calling
foo
, must compile (or make
foo
a regular non-suspending fun works as well 😀)
(also, no need to make
myStruct
a suspend fun if you are not calling
callback
from it...)
Copy code
private fun myStruct(): MyStruct = MyStruct(1) {
    foo()
}

suspend fun foo() {}

private data class MyStruct(
    val a: Int,
    val callback: (suspend () -> Unit)?
)
i

iex

07/12/2020, 5:18 PM
@streetsofboston I did try that out but it didn't compile:
Modifier 'suspend' is not applicable to 'non-functional type'
(on the lambda's
suspend
)
s

streetsofboston

07/12/2020, 5:18 PM
Sorry, fixed my answer... Put the
(
in the correct place now.
i

iex

07/12/2020, 5:20 PM
ah thanks!
compiles 🙂
@Adam Powell
myStruct()
doesn't have to be actually suspended. I was just struggling to make the callback suspended (where I'm calling
send
on a
BroadcastChannel
)
d

Daniel

07/13/2020, 8:12 AM
callback needs to be a suspending lambda like they said
4 Views