scala类型系统:11) upper bounds & lower bounds

来源:互联网 发布:天天炫斗数据互通 编辑:程序博客网 时间:2024/05/12 02:13

scala类型系统:11) upper bounds & lower bounds

在Java泛型里表示某个类型是Test类型的子类型,使用extends关键字:

<T extends Test>//或用通配符的形式:<? extends Test>

这种形式也叫upper bounds(中文为上限或上界),同样的意思在scala的写法为:

[T <: Test]//或用通配符:[_ <: Test]

upper bounds适用于把泛型对象当作数据的提供者(生产者)的场景下:

scala>  def pr(list : List[_ <: Any]) {             list.foreach(print)         }

Lower Bounds

在Java泛型里表示某个类型是Test类型的父类型,使用super关键字:

<T super Test>//或用通配符的形式:<? super Test>

这种形式也叫lower bounds(中文为下限或下界),同样的意思在scala的写法为:

[T >: Test]//或用通配符:[_ >: Test]

lower bound适用于把泛型对象当作数据的消费者的场景下:

scala>  def append[T >: String] (buf : ListBuffer[T])  = {                  buf.append( "hi")        }

基本上与java一致,不过在复杂一点的情况下,对多重界定,有一些差异:

Java里,T 同时是 A 和 B 的子类型,称为multiple bounds

<T extends A & B>

Scala里对上界和下界不能有多个,不过变通的做法是使用复合类型(compund type):

[T <: A with B]

而对于lower bounds,在java里则不支持multiple bounds的形式:

<T super A & B> //java不支持

Scala里对复合类型同样可以使用lower bound

[T >: A with B]

因为Scala里对于 A with B相当于 (A with B),仍看成一个类型,参考复合类型

转载自:http://hongjiang.info/scala/   推荐大家阅读下这位大哥出版的书《Scala函数式编程》

0 0
原创粉丝点击