Search code examples
scalaarraybuffer

How could assign ArrayBuffer[Implementation] to ArrayBuffer[Interface] in Scala


I'm trying to do something like below in Scala

val buffer1:ArrayBuffer[Element] = ???
val buffer:ArrayBuffer[IElement] = buffer1

Which the IElement is my custom interface, and the Element is one element of the implementation. But the scala compiler shows me an error like this:

Expression of type ArrayBuffer[Element] doesn't conform to expected type ArrayBuffer[IElement]

How could I get it passed by the compiler?
Does the scala ArrayBuffer support that?


Solution

  • Take a look to the Scala Type Hierarchy in here. As you can see the Int type does not extend from Object so you can not initialize an ArrayBuffer[Object] with an Int value. You have to change the objet to AnyVal. Besides, it is invariant in its type. That means that two declarations like:

    var buffer:ArrayBuffer[AnyVal] = ArrayBuffer.apply(1)
    

    and

    var buffer2:ArrayBuffer[Int] = ArrayBuffer.apply(1)
    

    They are not the same so if you try to do something like:

    buffer = buffer2
    

    The compiler gives you the following error:

    error: type mismatch;
            found   : scala.collection.mutable.ArrayBuffer[Int]
            required: scala.collection.mutable.ArrayBuffer[AnyVal]
           Note: Int <: AnyVal, but class ArrayBuffer is invariant in type A.
           You may wish to investigate a wildcard type such as `_ <: AnyVal`. (SLS 3.2.10)