3 ms·
> A major difference from Java in Scala is, that container types are not-variant by default! Only arrays are variant "by default" in java (which was a huge mis
by greydius 11y ago
> A major difference from Java in Scala is, that container types are not-variant by default!
Only arrays are variant "by default" in java (which was a huge mistake). Variance for generic collections is specified at use, not at the type definition level.
> This means that if you have a container defined as Box[A], and then use it with a Fruit in place of the type parameter A, you will not be able to insert an Apple (which IS-A Fruit) into it.
No. What this really means is that you can't assign an instance of Box[Apple] to a val/var of type Box[Fruit].
- thomasahle 11y agoThe last part makes sense, no? If you could do List<Fruit> fruits = apples Then you could add an orange to the fruits list, and it would appear among the apples. It doesn't seem like you can fix this without immutability?
- deleted 11y ago[deleted]
- catnaroek 11y agoThe problem with what Java calls a `List` is that it really isn't a list. It's a mutable cell, whose contents at any given point in time is a list. The methods of the mutable cell let you replace the list with a new one, which happens to be partially based on the old one. Also, because Java's data structures are usually ephemeral, the new list can be created in the same place where the old list was. A type constructor of lists (which Java's standard library doesn't have to the best of my knowledge) is covariant on its element type, but a type constructor of mutable cells is invariant on its content type.
- ohnomrbill 11y agoIf you really did have a case where your list is a list of apples, wouldn't you type: List<Apple> apples = aps If you're using a general type Fruit, and can't stand any fruit that isn't an apple, you probably need to use the more specific Apple type.
- thomasahle 11y agoI mean, the problem of assigning `fruits = aps` is not that you get apples in your fruit list, but that now elements added to fruit (not of apple type) also get added to `aps`. The assignment sort of goes both ways like that.
- ohnomrbill 11y agoAh, your point makes more sense now. Immutability would help a lot here, it seems.