Search code examples
javakotlintype-conversion

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


I've imported a library into my code that uses Sealed Classes as Error Handling. The Library is written in Kotlin, and my code is in Java. Other than this line, things have gone okay.

Code Example of what I've tried to even hold the Resource:

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

The dogClient.fetchDog(String id) method uses a sealed class called Resource where it uses data classes to handle errors. When I try to do the above, it says it cannot access Kotlin.coroutines.Continuation.

Resource in T code:

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>()
}

I need to access the data on Success, and know when it throws an Error. The code in Kotlin would work something like this:

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

I am completely lost on how to translate this to Java and haven't found any articles/documentation to help me.


Solution

  • it says it cannot access 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).

    You can check this other answer for this specific problem. It basically boils down to providing a non-suspend function from the Kotlin code, which you will be able to call from Java.

    If you cannot modify the library, you can add a simple Kotlin file to your project to write this "bridge" function (but this means you'll need to setup Kotlin compilation in your project).