Relax requirement for foreach instruction's variable to be the type of the collection membership
Use of the foreach instruction is annoying if the collection's membership type is more general than the objects it's known to contain. For example, if I have a Collection containing Customer instances, I can't write the following:
foreach c in customers do
I get a compiler error - 6072 - Incompatible types.
To solve this, I need to resort to an Iterator:
c : Customer;
iter : Iterator;
iter := customers.createIterator();
while iter.next(c) do
When using an Iterator, if it encounters an object in the collection that can't be assigned to the type of the variable it raises a 1086 exception (Class of object is invalid in this context).
It would be nice if the compiler supported the same semantics for the foreach instruction too. The compile should check that the iteration variable is compatible with the membership of the collection (i.e. a sub-type of its membership type) but doesn't need to be the exact type or supertype.
I believe this wouldn't be a breaking change as all existing compiled code would still work with the relaxed scheme.
FileVision UK Ltd 12/01/2018 4:52:34 AM
I'd like to vote against this - compile time errors are better than runtime errors.
Having said that, for the case where different kinds of collections could be passed but they all have the same member type, maybe something like a small subset of generic types could be used e.g. all of CustomerArray, CustomerSet and CustomerDictionary would be compatible with Collection.
Software Medical Infomatics Limited 11/01/2018 10:17:22 AM
Yes, I like that idea too. Probably easier to do it as an enhancement to the syntax than to change the semantics of the existing instruction.
Brian Johnstone 11/01/2018 9:32:03 AM
Another possible option would be to add an 'as' modifier to the foreach statement, similar to the existing 'as' modifier on the create statement. This would mean existing type checking rules could remain unchanged and make it more explicit to someone looking at the code that you expect the collection to contain only instances compatible with the supplied. Then, for those scenarios where you 'know' the content is only of a specific type you could code "foreach in as do" and get a 1086 should it encounter an instance not compatible with .