从 Java 调用 Kotlin 挂起函数

Gab*_*man 7 java kotlin kotlin-coroutines

我有一个 Kotlin 库,我试图从 Java 调用它。我以前没有使用过 Kotlin。

Kotlin库函数如下:

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

我如何从 Java 中调用它?到目前为止我已经尝试过:

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
Run Code Online (Sandbox Code Playgroud)

我从未看到任何控制台输出。看起来延续从未被调用,或者它在另一个上下文中运行。我仔细研究了其他答案,协程似乎已经经历了多次迭代 - 我找不到对我来说真正有意义的解释。

我应该注意到我正在 Java 11 上运行。

如何简单地调用kotlin函数?

bro*_*oot 10

我建议甚至不要尝试。挂起函数从来就不是用于 Java 互操作的。

相反,在 Kotlin 端将其转换为 Java 可以理解的内容 - CompletableFuture

fun decodeAsync(jwt: String): CompletableFuture<UsefulThing> = GlobalScope.future { decode(jwt) }
Run Code Online (Sandbox Code Playgroud)

我们可以在单个模块中自由混合 Java 和 Kotlin 代码,因此您可以在项目中创建这样的包装器。

根据您的情况,您可以使用GlobalScope(在 Java 中我们没有结构化并发),或者您可以创建自定义CoroutineScope并手动处理其生命周期。