1、上界与下界:Upper bound,lower bound
作用:规定泛型的取值范围
Int x
100 <= x <= 200
下界 上界
(*)规定泛型的取值范围
举例:定义一个泛型:T
类的继承关系 A---->B----->C----->D 箭头指向子类
可以规定T的取值范围 D <: T <: B
T 的取值范围只能是 B C D
<: 就是上下界表示方法
(*)定义:
上界 s <: T 规定了S的类型必须是T的子类或本身
下界 u >: T 规定了U的类型必须是T的父类或本身
scala> def addTwoString[T<:String](x:T,y:T) = x + " **** " + y
addTwoString: [T <: String](x: T, y: T)String
scala> addTwoString("Hello","123")
res9: String = Hello **** 123
scala> addTwoString(1,2)
<console>:14: error: inferred type arguments [Int] do not conform to method addTwoString's type parameter bounds [T <: String]
addTwoString(1,2)
^
<console>:14: error: type mismatch;
found : Int(1)
required: T
addTwoString(1,2)
^
<console>:14: error: type mismatch;
found : Int(2)
required: T
addTwoString(1,2)
报错原因:Int不是String类型。
解决:1和2转换成字符串再调用
scala> addTwoString(1.toString,2.toString)
res11: String = 1 **** 2
另外:可以使用 视图界定 来解决这个问题。
2、视图界定:View bound
是上界和下界的一种扩展
除了可以接收上界和下界规定的类型之外,还可以接收能够通过隐式转换过去的类型
用法 : %
def addTwoString[T<%String](x:T,y:T) = x + " **** " + y
含义:
1、可以接收String及其子类
2、可以接收能够转换成String的其他类型
scala> def addTwoString[T<%String](x:T,y:T) = x + " **** " + y
addTwoString: [T](x: T, y: T)(implicit evidence$1: T => String)String
scala> addTwoString(1,2)
<console>:14: error: No implicit view available from Int => String.
addTwoString(1,2)
报错解决:定义隐式转换函数,把int转换成String
scala> implicit def int2String(n:Int):String=n.toString
warning: there was one feature warning; re-run with -feature for details
int2String: (n: Int)String
scala> addTwoString(1,2)
res13: String = 1 **** 2
分析执行过程:
1、调用 int2String 方法,把Int转换成String(scala在后台调用,不需要显示调用)
2、调用addTwoString方法,拼接字符串
隐式转换函数,不需要显示调用它,它就能被调用。
scala> implicit def int2String2(n:Int):String="hehe"
warning: there was one feature warning; re-run with -feature for details
int2String2: (n: Int)String
scala> addTwoString(1,2)
<console>:16: error: ambiguous implicit values:
both method int2String of type (n: Int)String
and method int2String2 of type (n: Int)String
match expected type Int => String
addTwoString(1,2)
3、协变与逆变
了解概念即可
概念:
协变:泛型变量的值可以是本身类型或者其子类型
逆变:泛型变量的值可以是本身类型或者其父类型
表示:
协变 +
逆变 -