Reputation: 418
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?
Upvotes: 0
Views: 94
Reputation: 4123
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)
Upvotes: 1