Scala基础11——第11章:泛型

第11章 泛型

// Array[String] 使用了泛型为String的Array
def main(args:Array[String]):Unit={}

为什么要用泛型:如果使用Any的话,就需要进行强转,强转可能会出现一些意外情况

11.1 协变和逆变

class MyList[+T] // 协变

class MyList[-T] // 逆变

class MyList[T] // 不变

协变: Son是Father的子类,则MyList[Son]也是MyList[Father]的子类

协变: Son是Father的子类,则MyList[Son]也是MyList[Father]的父类

不变: Son是Father的子类,则MyList[Son] , MyList[Father]没有父子关系

object Test03{
    def main(args:Array[String]):Unit={
    	// 1 协变和逆变
        val child:Child = new Child 
        val child:Parent = new Child
        
        
        // val childList:MyCollection[Parent] = new MyCollection[Child] // 定义为不变,
        
        val childList:MyCollection2[Parent] = new MyCollection2[Child] // 定义为协变
        
        val childList2:MyCollection3[Child] = new MyCollection3[Parent] // 定义为协变
    }
    
    
}

class Parent{}
class Child extends Parent{}
class SubChild extends Child{}

class MyCollection[E] {}
class MyCollection2[+E] {}
class MyCollection3[-E] {}

11.2 泛型上下限

基本语法

class PersonList[ T <: Person ] // 泛型上限
// 可以是person的子类,或者自身

class PersonList[ T >: Person ] // 泛型下限
// 可以是person的父类,或者自身
object Test03{
    def main(args:Array[String]):Unit={
        
        // 上下限
        def test[A <: Child](a:A): Unit={
            println(a.getClass.getName)
        }
        
        // test[Parent](new Child) //!!!报错,超过上限
        test[Child](new Child)
        test[Child](new SubChild)
        
        
    }    
}

class Parent{}
class Child extends Parent{}
class SubChild extends Child{}

11.3 上下文限定

基本语法

def f[A:B](a:A) = println(a)
// 等价于
def f[A](a:A)(implicit arg:B[A]) = println(a)
// 把B作为隐式参数,且参数的泛型是A
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值