1.符号

2018-12-20  本文已影响0人  丹之

1. 上下界约束符号 <: 与 >:

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的下界。

2.协变与逆变符号+T, -T

“协变”是指能够使用与原始指定的派生类型相比,派生程度更大的类型。e.g. String => AnyRef

“逆变”则是指能够使用派生程度更小的类型。e.g. AnyRef => String

【+T】表示协变,【-T】表示逆变

3. 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 = ...

4.Scala's @ operator

It enables one to bind a matched pattern to a variable. Consider the following, for instance:

val o: Option[Int] = Some(2)

You can easily extract the content:

o match {
  case Some(x) => println(x)
  case None =>
}

But what if you wanted not the content of Some, but the option itself? That would be accomplished with this:

o match {
  case x @ Some(_) => println(x)
  case None =>
}
上一篇 下一篇

猜你喜欢

热点阅读