![](/img/trans.png)
[英]How to transform a sealed Kotlin class into a Java class
[英]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.