Java中的Kotlin结果类型

vohkndzv  于 7个月前  发布在  Kotlin
关注(0)|答案(2)|浏览(61)

Kotlin引入了新的类型:Result。我使用它作为几个函数的完成处理程序,如下所示:

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

字符串
不幸的是,我不能在java中使用它。Java没有建议我使用getOrbit或isSuccess/isFailure这样的getter。
我该怎么用?谢谢

efzxgjgh

efzxgjgh1#

在Java中没有对Result类型的标准支持,但您可以始终使用第三方库,如HubSpot/algebra

zsbz8rwp

zsbz8rwp2#

虽然不能直接在java中获取Kotlin.Result,但可以使用以下方法获取:

/**
 * 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})"
}

字符串
在 *.kt**文件中

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


在 *.java**中使用myFunction

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

相关问题