Recently I've noticed that variance annotations can be used in type aliases. Here is example from Predef
:
type Function[-A, +B] = Function1[A, B]
And I started to think, where it could be used. Obviously, you can't change variance to opposite, or make an invariant type to behave as co- or contravariant. Compiler will throw an error, like this
scala> type BrokenFunc[+T, -R] = Function1[T, R]
<console>:7: error: covariant type T occurs in contravariant position in type
[+T, -R]T => R of type BrokenFunc
But, you can make some variant type to behave like invariant (at least, compiler wouldn't argue with that). So, I tried to make an invariant version of List
scala> type InvList[T] = List[T]
defined type alias InvList
But this new invariant List
still behaves just like it's original covariant version:
scala> val l: InvList[String] = List("foo")
l: InvList[String] = List(foo)
scala> val anyList: InvList[Any] = l
anyList: InvList[Any] = List(foo)
So, what I am missing? What's the purpose of variance annotations in type aliases? Can you give an example of type alias with variance annotations, that will differ from original type.
,Map> without having to define a dedicated class with all required consequences.
– Thipor Kong May 10 '12 at 07:43