gpt4 book ai didi

scala - 除了输入/输出参数,类型变化的其他用途是什么?

转载 作者:行者123 更新时间:2023-12-04 17:59:52 24 4
gpt4 key购买 nike

我的理解是类型差异用于以下情况:

  • 如果是泛型类型 G有类型参数 T1 , 它显示为 G 的一种参数类型方法,然后 G可以在 T1逆变 .

  • 如果 G有类型参数 T2 ,它显示为 G 的方法(或 ctor)的任何返回值的类型, 然后 G可以在 T2协变 .

如果我将上面句子中的 can be 替换为 should be 会怎样?还有其他协变和反变用法的情况吗?什么时候以及为什么要使类型协变和逆变?

最佳答案

引用自规范,第 4.5 节方差注释:

Variance annotations indicate how instances of parameterized types vary with respect to subtyping (§3.5.2). A '+' variance indicates a covariant dependency, a '-' variance indicates a contravariant dependency, and a missing variance indication indicates an invariant dependency. A variance annotation constrains the way the annotated type variable may appear in the type or class which binds the type parameter. In a type definition type T [tps] = S, or a type declaration type T [tps] >: L <: U type parameters labeled +' must only appear in covariant position whereas type parameters labeled '-' must only appear in contravariant position.

因此默认情况下类型参数被认为是不变的。您必须明确地将类型参数注释为协变或逆变如果你想使用它。此外,在根本不使用的类型参数上使用变体注释是完全合法的(尽管他可能没那么有用)。例如:


scala> class A[+T, -S] {def myMethod(s: String) = println(s)}
defined class A

scala> class A2[T] {def myMethod(t: T) = println(t)}
defined class A2

scala> class A3[-T] {def myMethod(t: T) = println(t)}
defined class A3

scala> val a1 = new A2[Any]
a1: A2[Any] = A2@1cd1cea

scala> val a2: A2[Int] = a1
:6: error: type mismatch;
found : A2[Any]
required: A2[Int]
val a2: A2[Int] = new A2[Any]

scala> val a3 = new A3[Any]
a3: A3[Any] = A3@875dee

scala> val a4: A3[Int] = a3
a5: A3[Int] = A3@875dee

类 A3 上的方差注释,在这个例子中是逆变的,使得 A3[Any] 被认为是 A3[Int] 的子类型,使从实例 a4 到 a3 的分配合法。如果您不使用方差注释,则会失败。

关于scala - 除了输入/输出参数,类型变化的其他用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5272262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com