泛型
2023年12月30日大约 2 分钟约 333 字
协变和逆变
语法

说明
协变:Son 是 Father 的子类,则 MyList[Son] 也作为 MyList[Father]的“子类”。 逆变:Son 是 Father 的子类,则 MyList[Son]作为 MyList[Father]的“父类”。 不变:Son 是 Father 的子类,则 MyList[Father]与 MyList[Son]“无父子关系”。
泛型上下限
语法

说明
泛型的上下限的作用是对传入的泛型进行限定。
上下文限定
语法

说明
上下文限定是将泛型和隐式转换的结合产物,以下两者功能相同,使用上下文限定[A : Ordering]之后,方法内无法使用隐式参数名调用隐式参数,需要通过 implicitly[Ordering[A]] 获取隐式变量,如果此时无法查找到对应类型的隐式变量,会发生出错误。
package chapter09plus
object Test03_Generics {
def main(args: Array[String]): Unit = {
// 1. 协变和逆变
val child: Parent = new Child
//val childList: MyCollection[Parent] = new MyCollection[Child]
val childList: MyCollection[SubChild] = new MyCollection[Child]
// 2. 上下限
def test[A <: Child](a: A): Unit = {
println(a.getClass.getName)
}
// test[Parent](new Child) // 错误
test[Child](new Child)
}
}
// 定义继承关系
class Parent {}
class Child extends Parent {}
class SubChild extends Child {}
// 定义带泛型的集合类型
class MyCollection[-E] {}