sitepodmatt
02/14/2019, 6:13 AMgildor
02/14/2019, 6:15 AMtrathschlag
02/14/2019, 10:13 AMgildor
02/14/2019, 10:19 AMtrathschlag
02/14/2019, 10:31 AMsuspend fun runInScope(body: suspend () -> Unit) {
coroutineScope {
body()
}
}
fun main() {
runBlocking {
try {
runInScope {
launch {
throw RuntimeException("dead")
}
}
} catch (e: Exception) {
println("caught")
}
}
}
And this compiles fine but kills the whole application instead of printing caught
because somebody forgot to add CoroutineScope.
receiver to the body
parameter.
Correct code:
suspend fun runInScope(body: suspend CoroutineScope.() -> Unit) {
coroutineScope {
body()
}
}
fun main() {
runBlocking {
try {
runInScope {
launch {
throw RuntimeException("dead")
}
}
} catch (e: Exception) {
println("caught")
}
}
}
gildor
02/14/2019, 1:15 PMtrathschlag
02/14/2019, 1:28 PMlaunch
on the wrong receiver. If you change the signature of runInScope
, there is no visual change on the calling site but something completely different happens.gildor
02/14/2019, 11:30 PM