Sam
08/03/2023, 10:59 AMsuspend fun foo(): String = "foo"
abstract class Bar(val foo: String)
suspend fun main() {
val bar = object: Bar(foo()) {} // ❌ Suspension functions can be called only within coroutine body
}
Obviously it works fine if I instead write
suspend fun main() {
val foo = foo()
val scope = object: Bar(foo) {}
}
Javier
08/03/2023, 11:03 AMJavier
08/03/2023, 11:04 AMNicklas Jensen
08/03/2023, 11:04 AMBar(foo())
) actually compiled into the constructor of the anonymous class in this case? The constructor of the anonymous class is obviously not a suspend
function, and as such would not be able to call other suspend
functions.
E.g. the class of the anonymous class you're creating could also be expressed like this:
class AnonymousClass : Bar(foo()) {
}
suspend fun main() {
val bar = AnonymousClass()
}
Which wouldn't compile because the constructor of AnonymousClass
is not and cannot be a suspend
function.Sam
08/03/2023, 11:10 AMNicklas Jensen
08/03/2023, 11:11 AMSam
08/03/2023, 12:10 PMJavier
08/03/2023, 12:25 PMstreetsofboston
08/03/2023, 12:40 PMfoo()
(temp variable) being captured, the call to foo()
itself s captured.
I agree with Javier and I'd report this, since it is, as you said, very unintuitive.Sam
08/09/2023, 2:04 PMSam
08/09/2023, 2:04 PM