Pass a Suspended-function reference as another function parameter

540 views Asked by At

I have created a function that should get a suspended function as its parameter, run it, and perform some operations with the results.

When I try to call this function and pass a function reference from a different class (let us call it "SomeClass" for example), I see the following error on intellij:

Type mismatch.

Required:
suspend (String, Int) → SomeType

Found:
KSuspendFunction3<OtherClass, String, Int, SomeType>

My function that should get a suspended function as a parameter:

private suspend fun performSomeOperation(
    block: suspend (String, Int) -> SomeType
) : Result<SomeValue> {
    .
    .
    .
}

The function I reference from "OtherClass"

suspend fun performOperation(id: String, value: Int): SomeType {
    .
    .
    .
}

The call to my function, passing OtherClass::performSomeOperation function reference as a parameter

updateRestartParam(OtherClass::performSomeOperation)
2

There are 2 answers

0
ran8080 On

Ok, so it appears this error was caused since I tried to pass a "Bound Callabele Reference", which means referencing a member function of a different class.

And Since Kotlin 1.1 you can do that, by prefixing the function reference operator with the instance:

updateRestartParam(otherClassInstance::performSomeOperation)
0
Tenfour04 On

The warning message has an unhelpful syntax for describing the parameter it found. OtherClass::performSomeOperation is really of type

suspend (OtherClass, String, Int) -> SomeType

or

suspend OtherClass.(String, Int) -> SomeType

They are treated equivalently when passed as a function parameter. As you found, otherClassInstance::performSomeOperation has the type you need. By specifying the instance, it is bound to the function so it is not one of its parameters.