/**
* 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;
});
}
2条答案
按热度按时间efzxgjgh1#
在Java中没有对
Result
类型的标准支持,但您可以始终使用第三方库,如HubSpot/algebra
。zsbz8rwp2#
虽然不能直接在java中获取Kotlin.Result,但可以使用以下方法获取:
字符串
在 *.kt**文件中
型
在 *.java**中使用
myFunction
。型