What should we do about casts to instances of generic types?


The spec says:

Specifically, all casts to instances of generic types are forbidden.

The following code needs to be, and is, statically
rejected. It constructs an array `a` of `Int{self==3}`'s – integers
are statically known to be 3.
The only number that can be stored into `a` is `3`.
Then (in the line that is rejected) it attempts to trick the compiler into
thinking that it is an array of `Int`, without restriction on the
elements, giving it the name `b` at that type.
The cast aa as Array[Int]` is a cast to an instance of a generic type,
and hence is forbidden.

But, if that cast were allowed to work, it could store `1` into the array
under the alias
`b`, thereby violating
the invariant that all the elements of the array are 3.
This could lead to program failures, as illustrated by the failing assertion.

Here's the code:

But the compiler doesn't do what the spec says.


  • There is no protection on line 8. The cast succeeds. This is the "instance of a generic type" which the spec said was forbidden.

  • Although a dynamic check is inserted in line 9, it is not triggered. I'm not sure what precisely is being checked, even, but I don't think it's the issue I'm worried about.

  • Igor thought that the compiler would issue a warning message about the cast. I thought that it would forbid the cast. It actually seems to peacefully allow the cast.

We need to decide what the right behavior here is, and either fix the compiler or the spec. So I'm posting this as a language design issue, but it should get redirected after we know what we're doing.






Imported User 59




Fix versions