您可以在 Result 类的声明中使用 Kotlin 提供的声明站点差异。
T
-> 默认情况下 T 是不变的
out T
-> 使 T 协变
in T
-> 使 T 成为协变的
例子:
sealed class Result<out T, R>(val left: T? = null, val right: R? = null) {
class Success<T, R>(data: T) : Result<T, R>(left = data)
class Error<T, R>(data: R) : Result<T, R>(right = data)
}
fun main() {
val res1 = Result.Success<String, Int>("Test")
val res2: Result<Any, Int> = res1 // compiles successfully, T is covariant
val res3: Result<String, Any> = res1 // doesn't compile, R is invariant (Type Mismatch)
}
函数可以将 Result 返回为:
fun returnResult(): Result<String, Int> {
val random = Random.nextBoolean() // random, for demonstration
retrun if(random) {
Result.Success("Success Example")
} else {
Result.Error(404)
}
}