When is @uncheckedVariance needed in Scala, and why is it used in GenericTraversableTemplate?

Posted by retronym on Stack Overflow See other posts from Stack Overflow or by retronym
Published on 2010-03-16T12:33:26Z Indexed on 2010/03/16 12:36 UTC
Read the original article Hit count: 233

Filed under:
|
|
|

@uncheckedVariance can be used to bridge the gap between Scala's declaration site variance annotations and Java's invariant generics.

scala> import java.util.Comparator import java.util.Comparator

scala> trait Foo[T] extends Comparator[T] defined trait Foo

scala> trait Foo[-T] extends Comparator[T] :5: error: contravariant type T occurs in invariant position in type [-T]java.lang.Object with java.util.Comparator[T] of trait Foo trait Foo[-T] extends Comparator[T] ^

scala> import annotation.unchecked._ import annotation.unchecked._

scala> trait Foo[-T] extends Comparator[T @uncheckedVariance] defined trait Foo

This says that java.util.Comparator is naturally contra-variant, that is the type parameter T appears in parameters and never in a return type.

Which begs the question, why is it also used in the Scala collections library:

trait GenericTraversableTemplate[+A, +CC[X] <: Traversable[X]] extends HasNewBuilder[A, CC[A] @uncheckedVariance]

What are the valid uses for this annotation?

© Stack Overflow or respective owner

Related posts about scala

Related posts about variance