加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala中的协方差逆变误差

发布时间:2020-12-16 18:13:02 所属栏目:安全 来源:网络整理
导读:我试着编译下面的代码: class A[-T]class B[-T] extends A[A[T]] 我收到以下错误: error: contravariant type T occurs in covariant position in type [-T]A[A[T]]{def init(): B[T]} of class B 为什么这是一个错误? 解决方法 这是一个错误,因为A [A [T
我试着编译下面的代码:

class A[-T]
class B[-T] extends A[A[T]]

我收到以下错误:

error: contravariant type T occurs in covariant position in type [-T]A[A[T]]{def <init>(): B[T]} of class B

为什么这是一个错误?

解决方法

这是一个错误,因为A [A [T]]在类型T中是协变的.

从Wikipedia开始的协变类型的定义:

Within the type system of a programming language,a typing rule or a
type constructor is:

  • covariant if it preserves the ordering of types (≤),which orders types from more specific to more generic;
  • contravariant if it reverses this ordering;

考虑以下:

class Fruit
class Banana extends Fruit

Banana <: Fruit
A[Banana] :> A[Fruit] // Because A is contravariant in type T
A[A[Banana]] <: A[A[Fruit]] // Again because A is contravariant in type T

最后一个语句意味着A [A [T]]是协变的,因为它保留了类型的排序,从更具体到更通用.

所以有可能做到:

scala> type AA[+T] = A[A[T]]
defined type alias AA

scala> type AAA[-T] = A[A[A[T]]]
defined type alias AAA

但以下将导致错误:

scala> type AA[-T] = A[A[T]]
<console>:15: error: contravariant type T occurs in covariant position in type [-T]A[A[T]] of type AA
       type AA[-T] = A[A[T]]
            ^

scala> type AAA[+T] = A[A[A[T]]]
<console>:15: error: covariant type T occurs in contravariant position in type [+T]A[A[A[T]]] of type AAA
       type AAA[+T] = A[A[A[T]]]
            ^

最后返回到原始问题,因为基类A [A [T]]在类型T中通过构造是协变的,所以在类B定义中存在相同的方差规则违反.

为了理解它被禁止的原因,让我们假设它是可能的:

class B[-T] extends A[A[T]]

在这种情况下,我们得到:

B[Fruit] <: B[Banana] <: A[A[Banana]]

所以

val fruits: B[Fruit] = new B[Fruit]
val bananas1: B[Banana] = fruits
val bananas2: A[A[Banana]] = bananas1

现在我们有一个A [a [香蕉]]的值香蕉2,它指出A [A [水果]]的一个例子,它违反了类型安全,因为A [A [香蕉]]&lt ;: A [A [水果] ].

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读