Chen
Chen

Reputation: 58

Why scala List could take covariant type as paramenter in method +=

Scala List is declared as

sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with     Product with GenericTraversableTemplate[A, List] with LinearSeqOptimized[A, List[A]] with java.io.Serializable

The method to prepend an element to a List is declared as

def +:(elem: A): List[A]

As type A is covariant, why the compiler does not complain since A appears in the contravariant position in +:?

Upvotes: 2

Views: 95

Answers (1)

Eastsun
Eastsun

Reputation: 18859

Because its full signature is:

def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That

The doc what you mentioned in the question is just the simplified one, you need to check the full signature of the method.

Upvotes: 3

Related Questions