I have a class that inherits the Actor trait. In my code, I have a method that creates x numbers of this actor using a loop and another method that simply sends the Finish message to all of them to tell them to terminate. I made the kill method just take an array of Actor since I want to be able to use it with an array of any type of Actor. For some reason, however, when I pass a value of type Array[Producer], where Producer extends Actor, to a method that accepts the type Array[Actor], I get a type error. Shouldn’t Scala see that Producer is a type of Actor and automatically cast this?
I have a class that inherits the Actor trait. In my code, I have
Share
What you are describing is called covariance, and it is a property of most of the collection classes in Scala–a collection of a subtype is a subtype of the collection of the supertype. However, since
Arrayis a Java primitive array, it is not covariant–a collection of a subtype is simply different. (The situation is more complicated in 2.7 where it’s almost a Java primitive array; in 2.8 Array is just a plain Java primitive array, since the 2.7 complications turned out to have unfortunate corner cases.)If you try the same thing with an
ArrayBuffer(fromcollection.mutable<- edit: this part is wrong, see comments) or aList(<- edit: this is true) or aSet(<- edit: no,Setis also invariant), you’ll get the behavior you want. You could also create anArray[Actor]to begin with but always feed itProducervalues.If for some reason you really must use
Array[Producer], you can still cast it using.asInstanceOf[Array[Actor]]. But I suggest using something other than primitive arrays–anything you could possibly be doing with actors will be far slower than the tiny overhead of using a more full-featured collection class.