[fpc-pascal] Case statement for class introspection
Michael Van Canneyt
michael at freepascal.org
Sat Jan 15 09:24:12 CET 2022
On Sat, 15 Jan 2022, Ryan Joseph via fpc-pascal wrote:
>
>
>> 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.
myInstance match {
case TComponent => dosomething;
case TPersistent => dosomethingelse;
}
>
> 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.
I don't see how an inline variable helps with the casting mess. You'll
always need a cast.
What I do is
Var
MyInstance : TObject;
MyNeededClass : TMyNeededClass absolute myInstance:
>
> 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;
See above for the solution.
Michael.
More information about the fpc-pascal
mailing list