在 Java 类中调用 Kotlin 挂起函数 [英] Call Kotlin suspend function in Java class
问题描述
假设我们有以下挂起函数:
Assume we have the following suspend function:
suspend fun doSomething(): List<MyClass> { ... }
如果我想在我现有的 Java 类之一(我现在无法将其转换为 Kotlin)中调用此函数并获取其返回值,我必须提供一个 Continuation>
作为其参数(显然).
If I want to call this function in one of my existing Java classes (which I'm not able to convert to Kotlin for now) and get its return value I have to provide a Continuation<? super List<MyClass>>
as its parameter (Obviously).
我的问题是,我怎样才能实现一个.特别是它的 getContext
getter.
My question is, How can I implement one. Specially its getContext
getter.
推荐答案
首先,将 org.jetbrains.kotlinx:kotlinx-coroutines-jdk8
模块添加到您的依赖项中.在您的 Kotlin 文件中定义以下与编写异步 API 的 Java 风格相对应的异步函数:
First, add org.jetbrains.kotlinx:kotlinx-coroutines-jdk8
module to your dependencies. In your Kotlin file define the following async function that corresponds to Java style of writing async APIs:
fun doSomethingAsync(): CompletableFuture<List<MyClass>> =
GlobalScope.future { doSomething() }
现在使用 Java 中的 doSomethingAsync
,就像您在 Java 世界中使用其他异步 API 一样.
Now use doSomethingAsync
from Java in the same way as you are using other asynchronous APIs in the Java world.
这篇关于在 Java 类中调用 Kotlin 挂起函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!