Scala泛型详解(第十一章:协变和逆变、泛型上下限、上下文限定)

缺乏、安全感 2024-03-26 12:49 168阅读 0赞

Scala泛型

    • 11.1 协变和逆变
    • 11.2 泛型上下限
    • 11.3 上下文限定

11.1 协变和逆变

1)语法

class MyList[+T]{ //协变
}
class MyList[-T]{ //逆变
}
class MyList[T] //不变

2)说明

  • 协变:Son 是 Father 的子类,则 MyList[Son] 也作为 MyList[Father]的“子类”。
  • 逆变:Son 是 Father 的子类,则 MyList[Son]作为 MyList[Father]的“父类”。
  • 不变:Son 是 Father 的子类,则 MyList[Father]与 MyList[Son]“无父子关系”。
    3)实操

    //泛型模板
    //class MyList{}
    //不变
    //class MyList[T]{}
    //协变
    //class MyList[+T]{}
    //逆变
    //class MyList[-T]{}
    class Parent{

    1. }

    class Child extends Parent{

    1. }

    class SubChild extends Child{

    1. }

    object Scala_TestGeneric {

    def main(args: Array[String]): Unit = {

    //var s:MyList[Child] = new MyList[SubChild]

    }
    }

11.2 泛型上下限

1)语法

Class PersonList[T <: Person]{ //泛型上限
}
Class PersonList[T >: Person]{ //泛型下限
}

2)说明

泛型的上下限的作用是对传入的泛型进行限定。

3)实操

  1. class Parent{
  2. }
  3. class Child extends Parent{
  4. }
  5. class SubChild extends Child{
  6. }
  7. object Scala_TestGeneric {
  8. def main(args: Array[String]): Unit = {
  9. //test(classOf[SubChild])
  10. //test[Child](new SubChild)
  11. }
  12. //泛型通配符之上限
  13. //def test[A <: Child](a:Class[A]): Unit ={
  14. // println(a)
  15. //}
  16. //泛型通配符之下限
  17. //def test[A >: Child](a:Class[A]): Unit ={
  18. // println(a)
  19. //}
  20. //泛型通配符之下限 形式扩展
  21. def test[A >: Child](a:A): Unit ={
  22. println(a.getClass.getName)
  23. }
  24. }

11.3 上下文限定

1)语法

def f[A : B](a: A) = println(a) //等同于 def fA(implicit arg:B[A])=println(a)

2)说明

上下文限定是将泛型和隐式转换的结合产物,以下两者功能相同,使用上下文限定[A :
Ordering]之后,方法内无法使用隐式参数名调用隐式参数,需要通过 implicitly[Ordering[A]]
获取隐式变量,如果此时无法查找到对应类型的隐式变量,会发生出错误

  1. implicit val x = 1
  2. val y = implicitly[Int]
  3. val z = implicitly[Double]

3)实操

  1. def f[A:Ordering](a:A,b:A) =implicitly[Ordering[A]].compare(a,b)
  2. def f[A](a: A, b: A)(implicit ord: Ordering[A]) = ord.compare(a, b)

发表评论

表情:
评论列表 (有 0 条评论,168人围观)

还没有评论,来说两句吧...

相关阅读