Variance in Scala

本文探讨了Scala中参数化类型如List[T]的协变和逆变概念。当A是B的子类时,如果List[A]是List[B]的子类,那么称为协变;反之,如果List[B]是List[A]的子类,则为逆变。在Scala终端中尝试不同的案例,可以看到协变位置(返回类型定义位置)和逆变位置(参数类型定义位置)的区别。

Covariance & Contravariance & Variance

Given one parameterized type like List[T], with type A and B where A is a subclass of B, if List[A] is subclass of List[B], then we call it Covariance, else if List[B] is subclass of List[A], it's Contravariance. Type like List[T] which supports Covariance or Contravariance is called variance.


Covariant position & Contravariant position

Input below commands in scala terminal and see the output


Case 1:

class Test[+A] {def f(a: A){}}    - - - - - - - - - - - - - - - -1 

<console>:11: error: covariant type A occurs in contravariant position in type A of value a


Case 2:

class Test[-A] {def f(a: A){}} - - - - - - - - - - - - - - - -2

defined class Test


Case 3:

class Test[+A]{def f():A={...}} - - - - - - - - - - - - - - - -3

defined class Test


Case 4:

class Test[-A]{def f():A={...}} - - - - - - - - - - - - - - - -4

<console>:11:error: contravariant type A occurs in covariant position in type ()A of method f



Covariant position: position where defined the return type

Contravariant position: position where defined the arguments type




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值