DEADBEEF
DEADBEEF

Reputation: 2270

Kotlin result type in java

Kotlin introduced the new type: Result. I use it as a completion handler of several functions like this:

fun myFunction(completion: (Result<Boolean>) -> Unit)

Unfortunately I cannot use it in java. Java doesn't propose me getters like getOrNull or even isSuccess/isFailure.

How could I use it? Thanks

Upvotes: 11

Views: 4675

Answers (3)

Victor Nazarov
Victor Nazarov

Reputation: 835

I'm a maintainer of the https://github.com/sviperll/result4j project that was created specifically to provide a Result-type for Java-programmers.

Upvotes: 1

SakurajimaMaii
SakurajimaMaii

Reputation: 61

Although you cannot get kotlin.Result directly in java, you can use the following method to get it:

/**
 * ResultCompat.
 *
 * It is intended to solve the problem of being unable to obtain [kotlin.Result] in java.
 */
class ResultCompat<T>(val result: Result<T>) {

    companion object {
        /**
         * Returns an instance that encapsulates the given [value] as successful value.
         */
        fun <T> success(value: T): ResultCompat<T> = ResultCompat(Result.success(value))

        /**
         * Returns an instance that encapsulates the given [Throwable] as failure.
         */
        fun <T> failure(throwable: Throwable): ResultCompat<T> =
            ResultCompat(Result.failure(throwable))
    }

    /**
     * Returns `true` if [result] instance represents a successful outcome.
     * In this case [ResultCompat.isFailure] return `false` .
     */
    val isSuccess: Boolean
        get() = result.isSuccess

    /**
     * Returns `true` if [result] instance represents a failed outcome.
     * In this case [ResultCompat.isSuccess] returns `false`.
     */
    val isFailure: Boolean
        get() = result.isFailure

    /**
     * @see Result.getOrNull
     */
    fun getOrNull(): T? = result.getOrNull()

    /**
     * @see Result.exceptionOrNull
     */
    fun exceptionOrNull(): Throwable? = result.exceptionOrNull()

    override fun toString(): String =
        if (isSuccess) "ResultCompat(value = ${getOrNull()})"
        else "ResultCompat(error = ${exceptionOrNull()?.message})"
}

In *.kt file

fun myFunction(completion: (ResultCompat<String>) -> Unit){
    val result = ResultCompat.success("This is a test.")
    completion(result)
}

Using myFunction in *.java.

void myFunction(){
    myFunction(result -> {
        // You should not get result in java.
        result.getResult();
        // correctly
        result.exceptionOrNull();
        result.getOrNull();
        result.isSuccess();
        result.isFailure();
        return null;
    });
}

Upvotes: 2

Andrea Bergonzo
Andrea Bergonzo

Reputation: 5170

There is no standard support for Result like types in Java but you can always use third-party libraries like HubSpot/algebra.

Upvotes: 3

Related Questions