繁体   English   中英

如何访问 Kotlin 库密封类作为 Java 中的错误处理?

[英]How do you access Kotlin Library Sealed Classes as Error Handling in Java?

我已经将一个库导入到我的代码中,它使用密封类作为错误处理。 该库是用 Kotlin 编写的,我的代码在 Java 中。 除了这条线,一切都还好。

我什至尝试持有资源的代码示例:

String dogID = "1234";
DogClient dogClient = new dogClient(); //params not important.
Resource<DogDto> dogDtoResource = dogClient.fetchDog(dogID); //Problem Statement

dogClient.fetchDog(String id) 方法使用称为 Resource 的密封 class ,它使用数据类来处理错误。 当我尝试执行上述操作时,它说它无法访问 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 中的代码将这样工作:

when(dogClient.fetchDog(dogId)) {
    is Resource.Success -> result.data;
    is Resource.Error -> throw new Exception();

我完全不知道如何将其翻译为 Java 并且没有找到任何文章/文档来帮助我。

它说它无法访问 Kotlin.coroutines.Continuation

The problem is probably not the Resource sealed class then, but rather the fetchDog function you're trying to call is most likely a suspend function in Kotlin (using Kotlin coroutines).

您可以检查此特定问题的其他答案 它基本上归结为从 Kotlin 代码提供非暂停 function,您可以从 Java 调用该代码。

如果你不能修改库,你可以在你的项目中添加一个简单的 Kotlin 文件来编写这个“桥” function(但这意味着你需要在你的项目编译中设置 Kotlin)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM