scala类型系统:27) 回顾常见的type classes

在scala世界,type classes是一种非常常见的模式,我们回顾一下scala库的实现中有哪些采用这种模式的

1) Ordering

scala> def foo[T:Ordering] (l:List[T]) { 
            l.sorted.foreach(print) 
        }

scala> foo(List(2,3,1))
123

Ordering[_]抽象了大于、等于、小于等用于比较的方法。它是一个典型的type class

2) Numeric

scala> def foo[T:Numeric] (l:List[T]) { 
            print(l.sum) // List只对数字类型才能使用sum方法
        }

scala> foo(List(1,2,3))
6

scala> def bar[T:Numeric](a:T, b:T) {
            implicitly[Numeric[T]].plus(a,b) 
        }

scala> bar(2,3)

Numeric[_]对抽象了所有数字类型中的加、减、乘、除等操作。

3) Manifest/TypeTag/ClassTag 等

scala> def biuldArray[T:ClassTag](len:Int) = new Array[T](len)

scala> buildArray[Int](3)
res8: Array[Int] = Array(0, 0, 0)

4) <:<[-From, +To], =:=[From,To]

scala> def test[T](i:T) (implicit ev: T <:< java.io.Serializable) { 
            print("OK") 
        }

不要被它的两个类型参数和中缀方式给迷惑,这两个用于类型证明的泛型类,使用上也属于type class模式

在《scala in depth》中总结了type classes模式的几个优点:

1) Separation of abstractions (抽象分离)
2) Composability (可组合)
3) Overridable (可覆盖)
4) Type safety (类型安全)

发表评论

电子邮件地址不会被公开。 必填项已用*标注