本文最后更新于 2021-08-05 11:42:59
泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| case class Point[T](val x:T,val y:T){ def fun():T=x }
object Demo1 { def main(args: Array[String]): Unit = { val p =Point[Int](1,2) val x: Int = p.x val i: Int = p.fun() val j: Int = fun2[Int](1) val k: Int = fun2(1) } def fun2[T](x:T)=x }
|
指定上下界,视图绑定
1 2 3 4 5 6 7 8 9 10 11 12 13
| object Demo2 { def main(args: Array[String]): Unit = { println(compare[BigInt](1,2))
}
def compare[T <: Ordered[T]](x:T,y:T)={ if (x < y) x else y } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| abstract class Animal{ val name:String }
abstract class Pet extends Animal{
}
class Dog extends Pet{ override val name:String = "dog" } class Cat extends Pet{ override val name:String = "cat" }
object demo3 { def main(args: Array[String]): Unit = { showName(new Dog) showName(new Dog) getPet()
println(max[Int](1, 2))
}
def showName[T <:Pet](x:T)={ println(x.name) }
def getPet[T >:Pet]():Pet={ new Dog }
def max[T <% Ordered[T]](x:T,y:T): Unit ={ if (x < y) x else y } }
|
不变,协变,逆变
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class MyList[T]
class Father
class Son extends Father
object Demo5 { def main(args: Array[String]): Unit = { val a: Father = new Son
var fList: MyList[Father] = new MyList[Father] var sList: MyList[Son] = new MyList[Son] }
}
|
23泛型
https://jiajun.xyz/2020/11/18/scala/23泛型/