Scala - 泛型

泛型

下面是相似于java的泛型,有三个类Shape(形状)、Rectangle(长方形)、Square(正方形)。Shape是Rectangle的父类,Rectangle是Square的父类。因此咱们定义变量的时候,能够声明他为Shape类型,在new的时候给具体的类型。
Draw1这里有个泛型T,咱们能够看到定义变量的时候,这里的类型是不能有父子类关系的。java

object GenericDemo {
  def main(args: Array[String]): Unit = {
    val shape1: Shape = new Shape()
    var shape2: Shape = new Rectangle()
    var shape3: Shape = new Square()
    val draw1: Draw1[Shape] = new Draw1[Shape]()
    // val draw2: Draw1[Shape] = new Draw1[Rectangle]() // error
    // val draw3: Draw1[Shape] = new Draw1[Square]() // error
  }
}

class Shape {

}

class Rectangle extends Shape {

}

class Square extends Rectangle {

}

class Draw1[T]() {

}

协变和逆变

上面不能编译是由于Draw1[Shape]和new Draw1[Rectangle]并无父子关系,Scala经过协变能够让他们有父子关系:
在泛型T前面加一个+ide

class Draw2[+T]() {

}

而后在main函数中就能够调用了:函数

val draw2: Draw2[Shape] = new Draw2[Rectangle]()
val draw3: Draw2[Shape] = new Draw2[Square]()

scala中还有逆变,就是颠倒Draw3[T]的父子关系:
在泛型T前面加一个-scala

class Draw3[-T]() {

}

而后在main函数中就能够调用了:code

val draw4: Draw3[Rectangle] = new Draw3[Shape]()
val draw5: Draw3[Square] = new Draw3[Shape]()

上界下界

上界下界就是定义泛型的边界。
好比Draw2经过<:Shape2来定义泛型的上界,那Draw2的参数就是Shape2类以及子类。printInfo方法是Shape2的方法,因此printInfo中能够直接调用。t.printInfo()方法,
Draw3经过>:Rectangle2来定义泛型的下界,那Draw3的参数就是Rectangle2类以及父类,此时他只有Any的方法。get

object GenericDemo2 {
  def main(args: Array[String]): Unit = {
    val draw1: Draw2[Shape2] = new Draw2(new Shape2())
    val draw2: Draw2[Shape2] = new Draw2(new Rectangle2())
    val draw3: Draw2[Shape2] = new Draw2(new Square2())
    draw1.printInfo() // 形状
    draw2.printInfo() // 长方形
    draw3.printInfo() // 正方形
    println("-------------")
    val draw4: Draw3[Shape2] = new Draw3(new Shape2())
    val draw5: Draw3[Rectangle2] = new Draw3(new Rectangle2())
    //val draw6: Draw3[Square2] = new Draw3(new Square2()) // error
    draw4.printInfo() // class com.scala.learn12.Shape2
    draw5.printInfo() // class com.scala.learn12.Rectangle2
    // draw3.printInfo()
  }
}

class Shape2 {
  def printInfo(): Unit = {
    println("形状")
  }
}

class Rectangle2 extends Shape2 {
  @Override
  override def printInfo(): Unit = {
    println("长方形")
  }
}

class Square2 extends Rectangle2 {
  @Override
  override def printInfo(): Unit = {
    println("正方形")
  }
}

class Draw2[T <: Shape2](t: T) {
  def printInfo(): Unit = {
    t.printInfo()
  }
}

class Draw3[T >: Rectangle2](t: T) {
  def printInfo(): Unit = {
    println(t.getClass())
  }
}
相关文章
相关标签/搜索