Scala Type Parameters & Variance

Type Parameters

Similar to C++ templates or Java generics. These can apply to classes, traits or functions.
class MyClass[T](arg1: T) { ... }  
new MyClass[Int](1)  
new MyClass(1)   // the type is being inferred, i.e. determined based on the value arguments  
It is possible to restrict the type being used, e.g.
def myFct[T <: TopLevel](arg: T): T = { ... } // T must derive from TopLevel or be TopLevel
def myFct[T >: Level1](arg: T): T = { ... }   // T must be a supertype of Level1
def myFct[T >: Level1 <: TopLevel](arg: T): T = { ... }

Variance

Given A <: B
If C[A] <: C[B], C is covariant
If C[A] >: C[B], C is contravariant
Otherwise C is nonvariant
class C[+A] { ... } // C is covariant
class C[-A] { ... } // C is contravariant
class C[A]  { ... } // C is nonvariant

For a function, if A2 <: A1 and B1 <: B2, then A1 => B1 <: A2 => B2.
Functions must be contravariant in their argument types and covariant in their result types, e.g.
trait Function1[-T, +U] {
  def apply(x: T): U
} // Variance check is OK because T is contravariant and U is covariant

class Array[+T] {
  def update(x: T)
} // variance checks fails

评论

此博客中的热门博文

Nu förbjuder Kina handel med elfenben

Fader av pingyins

Kineserna vill köpa Volvos kompetens