Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Array[T forSome { type T; }] mean Array[Any]

I'm reading the article "Existential types in Scala", and found something I can't understand:

Array[T] forSome { type T; }
Array[T forSome { type T; }]

They look almost identical, but they're in fact very different. The first is the type of all arrays, whatever their type parameter. The second is Array[Any].

Why are they so different, and especially, why does the second one mean Array[Any]?

like image 805
Freewind Avatar asked Mar 29 '14 16:03

Freewind


1 Answers

It should not be surprising that changing the positions of brackets may alter the meaning a lot. A bit like if you switch ∃ and ∀

The first one means : there is some type T such that this is an Array[T]. So this is satisfied by Array[String], Array[Int], etc. The array is homogenous, but we don't know on which type.

The second one means : for each element of the array, there is some type T, such that the element is of type T. Which is no constraint at all, so it is just Array[Any]. Having the forSome inside the square brackets, may be useful if you do e.g.

Array[Set[T] forSome {type T}]

It means the element of the array are all Sets, but there might be a both a Set of Int and a Set of String in the same array.


Regarding Rich Oliver's comment about type erasure: this is mostly a compile time thing, and they are indeed different. In the first case, it is an array whose element type we do not know. So we cannot do e.g a(0) = 1, because it might be well be an Array[String]. On the opposite, with the second type, it is an Array[Any], and a(0) = 1 is ok.

like image 192
Didier Dupont Avatar answered Sep 19 '22 23:09

Didier Dupont