- Upper bound和Lower bound
用 :> 声明 Lower bound,即父类约束, A :> B, A必须是B的父类
用 <: 声明 Upper bound, 即子类约束, A <: B A必须是B的子类
Lower bound的例子
package ch6 object Test4 { println("Welcome to the Scala worksheet") class A { type B >: List[Int] def foo(a: B) = a } val x = new A { type B = Traversable[Int] } Set(1) x.foo(Set(1)) // val y = new A { type B = Set[Int]} // 编译错误 }
由此可见, A :> B的含义是: B的父类或与B有共同父类的类型
<:B通常不会用,因为它和 :B 的效果是一样的
2. 高阶类型
像高阶函数一样,有时一个类型需要另一个类型做参数。
type Callback[T] = Function1[T, Unit]
3.type lambda
类似与lambda 表达式表示的函数, 类型也可以这样灵活地定义,下面给出一个例子,这个例子来自
stackOverflow: http://stackoverflow.com/questions/8736164/what-are-type-lambdas-in-scala-and-what-are-their-benefits
trait Monad[M[_]] { def point[A](a: A): M[A] def bind[A, B](m: M[A])(f: A => M[B]): M[B] } class EitherMonad[A] extends Monad[({ type λ[α] = Either[A, α] })#λ] { def point[B](b: B): Either[A, B] def bind[B, C](m: Either[A, B])(f: B => Either[A, C]): Either[A, C] }
4.对于一个高阶类型A[T], A[T]的兼容性随T的具体类型的变化有三种情况
假设 S<: T
(1)invariant <=> A[S] 不兼容 A[T]
(2) covariant <=> A[S] <: A[T]
(3) contravariant <=> A[T] <: A[S]
原文:
A higher-kinded type that’s invariant implies that for any types T, A, and B if T[A] conforms to T[B] then A must be the equivalent type of B
T[A] conforms T[B]可以理解为 T[A]类型的引用可以赋给T[B]类型的对象
Covariance refers to the ability to substitute a type parameter with its parent type:
For any types T, A and B if T[A] conforms to T[B] then A <: B
5.mutable的类型必须是invariant的。 如Array
6.Function类型的参数类型,必须contraviriant的
package ch6 object Test4 { println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet def foo(x: Any):String = "Hello, I received a "+ x //> foo: (x: Any)String def bar(x: String): Any = foo(x) //> bar: (x: String)Any bar("test") //> res0: Any = Hello, I received a test foo("test") //> res1: String = Hello, I received a test }
foo的类型为 Function1[Any, String]
bar的类型为 Function1[String, Any]
foo可以赋值给bar