您如何访问密封的 Kotlin 库 类 作为 Java 中的错误处理?
How do you access Kotlin Library Sealed Classes as Error Handling in Java?
我已经将一个库导入到我的代码中,该库使用 Sealed 类 作为错误处理。该库是用 Kotlin 编写的,我的代码在 Java 中。除了这条线,一切都还好。
我试图保存资源的代码示例:
String dogID = "1234";
DogClient dogClient = new dogClient(); //params not important.
Resource<DogDto> dogDtoResource = dogClient.fetchDog(dogID); //Problem Statement
dogClient.fetchDog(String id) 方法使用密封的 class 调用资源,它使用数据 classes 来处理错误。当我尝试执行上述操作时,它说无法访问 Kotlin.coroutines.Continuation.
T代码中的资源:
sealed class Resource<in T> {
data class Success<T>(val data: T) : Resource<T>()
data class Error(val exception: Throwable, val statusCode: Int?) : Resource<Any>()
}
我需要访问有关 Success 的数据,并知道它何时抛出错误。 Kotlin 中的代码可以像这样工作 something:
when(dogClient.fetchDog(dogId)) {
is Resource.Success -> result.data;
is Resource.Error -> throw new Exception();
我完全不知道如何将其翻译成 Java,并且没有找到任何 articles/documentation 来帮助我。
it says it cannot access Kotlin.coroutines.Continuation
问题可能不是 Resource
密封 class,而是您尝试调用的 fetchDog
函数很可能是 suspend
函数Kotlin(使用 Kotlin 协程)。
您可以检查 以了解此特定问题。它基本上归结为从 Kotlin 代码提供非挂起函数,您将能够从 Java.
调用该函数
如果你不能修改库,你可以在你的项目中添加一个简单的 Kotlin 文件来编写这个“桥梁”功能(但这意味着你需要在你的项目中设置 Kotlin 编译)。
我已经将一个库导入到我的代码中,该库使用 Sealed 类 作为错误处理。该库是用 Kotlin 编写的,我的代码在 Java 中。除了这条线,一切都还好。
我试图保存资源的代码示例:
String dogID = "1234";
DogClient dogClient = new dogClient(); //params not important.
Resource<DogDto> dogDtoResource = dogClient.fetchDog(dogID); //Problem Statement
dogClient.fetchDog(String id) 方法使用密封的 class 调用资源,它使用数据 classes 来处理错误。当我尝试执行上述操作时,它说无法访问 Kotlin.coroutines.Continuation.
T代码中的资源:
sealed class Resource<in T> {
data class Success<T>(val data: T) : Resource<T>()
data class Error(val exception: Throwable, val statusCode: Int?) : Resource<Any>()
}
我需要访问有关 Success 的数据,并知道它何时抛出错误。 Kotlin 中的代码可以像这样工作 something:
when(dogClient.fetchDog(dogId)) {
is Resource.Success -> result.data;
is Resource.Error -> throw new Exception();
我完全不知道如何将其翻译成 Java,并且没有找到任何 articles/documentation 来帮助我。
it says it cannot access Kotlin.coroutines.Continuation
问题可能不是 Resource
密封 class,而是您尝试调用的 fetchDog
函数很可能是 suspend
函数Kotlin(使用 Kotlin 协程)。
您可以检查
如果你不能修改库,你可以在你的项目中添加一个简单的 Kotlin 文件来编写这个“桥梁”功能(但这意味着你需要在你的项目中设置 Kotlin 编译)。