[fpc-pascal] Case statement for class introspection
Ryan Joseph
genericptr at gmail.com
Sat Jan 15 03:14:39 CET 2022
> On Jan 15, 2022, at 8:30 AM, Michael Van Canneyt via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>
>> I saw a new syntax in Swift which I thought was clever and fits a pattern
>> I've seen before. Basically it's a case statement for class types which
>> lets you branch depending on which class type the class instance is at run
>> time.
>
> I think Scala did it before Swift.
What did it look like? Seems like an obvious feature any OOP language should have.
Swift has a compound switch statement which does lots of things. It's a little messy but it accomplishes this well. For example here they have a "case is" and "case let _ as" which tests for class type or casts to a local variable using "as".
switch object {
case is Message:
break
case let content as MessageContent:
break
case let attachment as Attachment:
break
default: break
}
Problem for Pascal is how to handle the casting mess. C languages (and Delphi now I guess) can do inline variable declarations to avoid the casting.
Come to think of it this a similar problem with for-loops where you want to loop over a collection of only certain types. For example:
for monster in monsters do
if monster is TZenChan then
TZenChan(monster).Dothis;
Swift does something similar as the switch which would look kind of like this:
for case monster as TZenChan in monsters do
TZenChan(monster).Dothis;
That syntax is not so nice but I like they're trying to help us manage class introspection using existing language constructs.
Regards,
Ryan Joseph
More information about the fpc-pascal
mailing list