# Type Bounds

• <: - uppper type bound, S <: T means that S is a subtype of T
• >: - lower type bound, S >: Tmeans that S is a supertype of T

• <% - view bound, S <% T expresses that S must come equipped with a view that maps its values into values of type T
• : - context bound,

# View Bounds & Context Bounds

## 什么是View Bound?

view bound 是Scala中的一种机制，使得能够将某一类型A当作另一类型B来使用。典型的用法如下:

## 什么是Context Bound?

Context bounds 在Scala 2.8.0中被引入, 是专门与所谓的 type class pattern 一起使用的, 尽管没那么简洁，但也还是实现了Haskell中type classes所提供的功能。

implicitly在这里被用作取得我们需要的隐式值，即一个类型为Ordering[A]的值，它定义了compare(a: A, b: A): Int这个方法。

## View Bounds是用来做什么的?

View bounds 被应用在 pimp my library 设计模式中，即：希望对已有类“添加”方法，但依然希望返回原类型的情形。如果你不需要返回原类型，那你就不需要view bound。

View bound最经典的用法是处理Ordered。取上一小节相同的例子，如果令泛型为Int，注意到Int并不是具备<方法的Ordered（尽管事实上是有隐式转换的），但函数返回值要求是Int，此时就需要一个view bound：

## Context Bounds是用来做什么的?

Context bounds 被用在 typeclass pattern 中，也就是Haskell中的type classes。 简单来说，这个设计模式通过一系列隐式适应从功能上实现了继承的一种替代方案。

# Generalized Type Constraints

<:<<%< 有相似的功能，但略微不同：

• A =:= B 表示A和B是严格相等的类
• A <:< B 表示A是B的subtype (和之前的type bounds<:类似)
• A <%< B means A must be viewable as B, possibly via implicit conversion (analogous to the simple type constraint <%)

# Manifest

The compiler knows more information about types than the JVM runtime can easily represent. A Manifest is a way for the compiler to send an inter-dimensional message to the code at runtime about the type information that was lost.

One common use of Manifests is to have your code behave differently based on the static type of a collection. For example, what if you wanted to treat a List[String] differently from other types of a List:

A reflection-based solution to this would probably involve inspecting each element of the list.

A context bound seems most suited to using type-classes in scala, and is well explained here by Debasish Ghosh: http://debasishg.blogspot.com/2010/06/scala-implicits-type-classes-here-i.html

Context bounds can also just make the method signatures more readable. For example, the above function could be re-written using context bounds like so:

# 小结

View bound中描述了一种隐式的转换

Context bound 描述了一种隐式的(value)。