Auto Cast in Scala

I have a class that inherits the Actor trait. In my code, I have a method that creates the xnumbers of this actor using a loop and another method that just sends a Finish message to all of them to tell them to stop acting. I made the kill method just take an actor array, 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 takes type Array [Actor], I get a type error. Should Scala see that the Producer is an actor type and automatically selects it?

+3
source share
1 answer

What you describe is called covariance, and it is a property of most collection classes in Scala - a subtype set is a subtype of a supertype collection. However, since it Arrayis a primitive array of Java, it is not covariant - the set of subtypes is simply different. (The situation is more complicated in 2.7, where it is an almost primitive Java array, in 2.8 Array is just a simple primitive Java array, since 2.7 complications were unsuccessful.)

If you try to do the same with ArrayBuffer(from collection.mutable<- edit: this part is incorrect, see comments) or List(<- edit: this is true) or Set(<- edit: no, is Setalso invariant), you will get the desired behavior. You can also create Array[Actor]for starters, but always load its values Producer.

- Array[Producer], .asInstanceOf[Array[Actor]]. - , - , , , .

+6

Source: https://habr.com/ru/post/1732631/


All Articles