Home > Software engineering >  Call a Kotlin suspend function from Java
Call a Kotlin suspend function from Java

Time:03-25

I have a Kotlin library that I'm attempting to call from Java. I haven't worked with Kotlin before.

The Kotlin library function is as follows:

suspend fun decode(jwt: String): UsefulThing {
    // does a bunch of stuff, removed for brevity.
    return otherthing.getUsefulThing(jwt)
}

How can I call this from Java? So far I've tried:

Continuation<UsefulThing> continuation = new Continuation<>() {

    @NotNull
    @Override
    public CoroutineContext getContext() {
        return EmptyCoroutineContext.INSTANCE;
    }

    @Override
    public void resumeWith(@NotNull Object o) {
        System.out.println("Result of decode is "   o);
    }

};

// Call decode with the parameter and continuation.
Object result = UsefulThingKt.decode(JWT, continuation);

// result is COROUTINE_SUSPENDED

I never see any console output. Looks like the continuation is never called, or it's run in another context. I've pored over other answers and coroutines seem to have gone through a number of iterations - I can't find an explanation that really makes sense to me.

I should note that I'm running on Java 11.

How can I simply call the kotlin function?

CodePudding user response:

I suggest to not even try. Suspend functions were never meant for Java interop.

Instead, convert it on the Kotlin side to something that Java understands - to CompletableFuture:

fun decodeAsync(jwt: String): CompletableFuture<UsefulThing> = GlobalScope.future { decode(jwt) }

We can freely mix Java and Kotlin code in a single module, so you can create such wrapper inside your project.

Depending on your case you could use GlobalScope (in Java we don't have structured concurrency) or you could create a custom CoroutineScope and handle its lifecycle manually.

  • Related