[英]Variance/Covariance generics in Kotlin
There is a sealed-class Result, which is parameterized with two types - success result (T) and error type (R).有一个密封类 Result,它被参数化为两种类型 - 成功结果(T)和错误类型(R)。
It is inheritered by two classes:它由两个类继承:
a.一个。 Success - data class, accepts object T in the constructor
成功 - 数据 class,在构造函数中接受 object T
b.湾。 Error - data class, accepts object R in the constructor
错误 - 数据 class,在构造函数中接受 object R
I need to create a function, which returns Result object.我需要创建一个 function,它返回结果 object。 The function has to be created in a way:
function 必须以某种方式创建:
Result<Number, String>
Result<Any, String>
Result<Int, CharSequence>
Result<Int, Any>
That is class Result must be covariant on T parameter and invariant on R parameter.即 class 结果在 T 参数上必须是协变的,在 R 参数上必须是不变的。
You can use the declaration-site variance provided by Kotlin in the declaration of your Result class.您可以在结果 class 的声明中使用 Kotlin 提供的声明站点差异。
T
-> By default T is invariant T
-> 默认情况下 T 是不变的out T
-> makes T covariant out T
-> 使 T 协变in T
-> makes T contavariant in T
-> 使 T 变Example:例子:
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)
}
A function can return Result as: function 可以返回结果为:
fun returnResult(): Result<String, Int> {
val random = Random.nextBoolean() // random, for demonstration
retrun if(random) {
Result.Success("Success Example")
} else {
Result.Error(404)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.