栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

大数据之Scala 泛型 完整使用(第十一章)

大数据之Scala 泛型 完整使用(第十一章)

大数据之Scala 泛型 完整使用

一、协变和逆变

1)语法2)说明3)实操 二、泛型上下限

1)语法2)说明3)实操 三、上下文限定

1)语法2)说明3)实操

一、协变和逆变 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)实操
package chapter09plus

object Test03_Generics {
  def main(args: Array[String]): Unit = {
    val child: Parent = new Child
    //    val childList: MyCollection[Parent] = new MyCollection[Child]
    val childList: MyCollection[SubChild] = new MyCollection[Child]
  }
}

//定义继承关系
class Parent {}
class Child extends Parent {}
class SubChild extends Child {}


class MyCollection[-e] {}
二、泛型上下限 1)语法
Class PersonList[T <: Person]{ //泛型上限
}
Class PersonList[T >: Person]{ //泛型下限
}
2)说明

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

3)实操
class Parent{}
class Child extends Parent{}
class SubChild extends Child{}
object Scala_TestGeneric {
 def main(args: Array[String]): Unit = {
 //test(classOf[SubChild])
 //test[Child](new SubChild)
 }
 //泛型通配符之上限
 //def test[A <: Child](a:Class[A]): Unit ={
 // println(a)
 //}
 //泛型通配符之下限
 //def test[A >: Child](a:Class[A]): Unit ={
 // println(a)
 //}
 //泛型通配符之下限 形式扩展
 def test[A >: Child](a:A): Unit ={
 println(a.getClass.getName)
 } }

package chapter09plus


object Test03_Generics {
  def main(args: Array[String]): Unit = {
    //2、上下限
    def test[A <: Child](a: A): Unit = {
      println(a.getClass.getName)
    }
    test[Child](new SubChild)

  }
}


//定义继承关系
class Parent {}

class Child extends Parent {}

class SubChild extends Child {}


三、上下文限定 1)语法

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

2)说明

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

3)实操
def f[A:Ordering](a:A,b:A) =implicitly[Ordering[A]].compare(a,b)
def f[A](a: A, b: A)(implicit ord: Ordering[A]) = ord.compare(a, b)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/751242.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号