简体   繁体   English

Kotlin 中的方差/协方差 generics

[英]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 必须以某种方式创建:

  • that the result of this function can be assigned to the variables of the following types:这个 function 的结果可以分配给以下类型的变量:
    Result<Number, String>
    Result<Any, String>
  • that the result of this function can NOT be assigned to the variables of the following types:该 function 的结果不能分配给以下类型的变量:
    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM