Code fragment in Kotlin
public actual fun <R, T> (suspend R.() -> T).createCoroutineUnintercepted(
receiver: R,
completion: Continuation<T>
): Continuation<Unit> {
val probeCompletion = probeCoroutineCreated(completion)
return if (this is BaseContinuationImpl)
create(receiver, probeCompletion)
else {
createCoroutineFromSuspendFunction(probeCompletion) {
(this as Function2<R, Continuation<T>, Any?>).invoke(receiver, it)
}
}
}
What I want to know is How (suspend R.() -> T)
AKA Function Type
can be recognized
as BaseContinuationImpl
which is a Classify Type
even to cast as `Function2'.
Any help will be appreciated.
CodePudding user response:
There are no separate function types and class types. Function types are just types that can be executed with specific arguments and specific return type. They are interchangeable with Function0
, Function1
, etc. interfaces and they contain a single invoke()
function.
We can implement a function type by our class:
class MyClass : (suspend () -> Unit) {
override suspend fun invoke() {}
}
Now, let's get this code:
val lambda: (suspend () -> Unit) = {}
After disassembling we see that our lambda is compiled to:
final class FooKt$foo$lambda$1 extends kotlin/coroutines/jvm/internal/SuspendLambda implements kotlin/jvm/functions/Function1 {
...
public final invoke(Ljava/lang/Object;)Ljava/lang/Object;
...
}
It extends SuspendLambda
which is a subtype of BaseContinuationImpl
. It also implements Function1
and contains invoke
function which makes it a function type.