- 上下界约束符号 <: 与 >:
这对符号个人觉得是里面最好理解的了,这对符号用于写范型类/函数时约束范型类型。
def using[A <: Closeable, B](closeable: A) (getB: A => B): B =
try {
getB(closeable)
} finally {
closeable.close()
}
例子中A <: Closeable(java.io.Cloaseable)的意思就是保证类型参数A是Closeable的子类(含本类),语法“A <: B"定义了B为A的上界;同理相反的A>:B的意思就是A是B的超类(含本类),定义了B为A的下界。
其实<: 和 >: 就等价于java范型编程中的 extends,super
-
协变与逆变符号+T, -T
协变:是指能够使用与原始指定的派生类型相比,派生程度更大的类型。e.g. String => AnyRef
逆变:则是指能够使用派生程度更小的类型。e.g. AnyRef => String
【+T】表示协变,【-T】表示逆变 -
view bounds(视界) 与 <%
<%的意思是“view bounds”(视界),它比<:适用的范围更广,除了所有的子类型,还允许隐式转换过去的类型
def method [A <% B](arglist): R = ...
等价于:
def method [A](arglist)(implicit viewAB: A => B): R = ...
或等价于:
implicit def conver(a:A): B = …
def method [A](arglist): R = ...
<% 除了方法使用之外,class声明类型参数时也可使用:
scala> class A[T <% Int]
defined class A
但无法对trait的类型参数使用 <%,
scala> trait A[T <% Int]
<console>:1: error: traits cannot have type parameters with context bounds `: ...' nor view bounds `<% ...'