2
class Test1(buf:Buffer[AnyRef])
class Test2(buf:Buffer[String]) extends Test(buf) 

Compiler error:

type mismatch; 
found : scala.collection.mutable.Buffer[String] 
required:  scala.collection.mutable.Buffer[Any] 
Note: org.msgpack.type.Value <: Any, but trait Buffer is invariant in type A. You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
tehlexx
  • 2,821
  • 16
  • 29
toughtalker
  • 461
  • 2
  • 6
  • 14

1 Answers1

3

Short answer: You can't add AnyRef to Buffer[String]:

val b: Buffer[AnyRef] = Buffer[String]()
b += new Object // ???

Buffer[String] can't be Buffer[AnyRef] because Buffer[T] is not covariant on type parameter T. It can't be declared covariant (Buffer[+T]) because there is usage of T in contravariant position (for instance in += method).

senia
  • 37,745
  • 4
  • 88
  • 129