Sunday, August 23, 2009

covariance-contravariance and constraining type params

If you define a class saying something like "class Test[A]" in scala then..
  • It is important to notice that Test is not a type but Test[Any] or Test[String] is.
  • At a place where Test[Any] is expected, you can not give Test[String] ... as was my notion due to mostly being a java programmer.
The idea of whether Test[String] should be considered subtype of Test[Any] is called "covariance". Only when you define your class like "class Test[+A]" then Test[String] will be considered subtype of Test[Any] and will be accepted wherever a Test[Any] is needed. '+' indicates that subtyping is covariant(flexible) in that parameter. In java, types are covariant by default.

Contravariance is exactly opposite of covariance and is supported with '-' symbol instead of '+'

Similarly, to constraint type parameters we can say things like...
class MyClass[V <: AnotherType]
This puts the constraint that V has to be a subtype of AnotherType and
class MyClass[V >: AnotherType]
puts the constraint that V has to be a type that is extended by AnotherType

No comments:

Post a Comment