Is this a bug, or an expected limitation? ```suspe...
# coroutines
s
Is this a bug, or an expected limitation?
Copy code
suspend 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
Copy code
suspend fun main() {
    val foo = foo()
    val scope = object: Bar(foo) {}
}
j
maybe the constructor function is not suspend and it is not inline too
you can create an inline invoke function in the companion to workaround this (I haven’t tried personally)
n
Isn't the call to the super constructor (
Bar(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:
Copy code
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.
s
Interesting, I hadn't considered that there's actually a constructor generated for the anonymous class! That makes sense, though the result is delightfully unintuitive
n
It's definitely ambiguous in this sense - I give you that 😄
s
Okay, so now I understand why it doesn’t work. Thanks for the insight! I still can’t decide if it’s a bug or not, though. I feel like there’s nothing in the rules of the language that say this shouldn’t work. It’s more of an implementation detail that requires knowing how the compiler will transform this code. 🤔
j
I would report it
👍 1
2
s
It's an interesting example of how capturing works for anonymous classes. Instead of the result of
foo()
(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.
👍 1
👍🏼 1
s
When I went to create an issue I found that it already exists 👍 https://youtrack.jetbrains.com/issue/KT-22984
I added an upvote