[fpc-devel] case is

Stefan Glienke sglienke at dsharp.org
Wed Mar 23 16:09:53 CET 2022


JEP 420 is hardly a misnomer because it is so much more than just type checking in a switch statement - hence pattern matching.
You can see in the various examples that you can combine all kinds of boolean expressions - C# has had this for quite a while and they are constantly improving it.
That also means that their order is important and the compiler cannot and does not do any sanity check.
Here is some nice article about the C# implementation: https://www.thomasclaudiushuber.com/2021/02/25/c-9-0-pattern-matching-in-switch-expressions/
Also I see in JEP 420 they thought of introducing variables for the different patterns to avoid having to write unnecessary boilerplate code or hardcasts - such as this:

static int coverage(Object o) {
    return switch (o) {
        case String s  -> s.length();
        case Integer i -> i;
        default -> 0;
    };
}

Ah well and using the switch statement as an expression so you get the complete package of nice and very expressive code.

> On 23/03/2022 13:44 Mattias Gaertner via fpc-devel <fpc-devel at lists.freepascal.org> wrote:
> 
>  
> Hi,
> 
> I just stumbled over the new Java feature "Pattern Matching for switch".
> https://openjdk.java.net/jeps/420
> IMO it is a misnomer, but it has some interesting ideas.
> 
> Basically for Pascal it is a case block using the "is" operator.
> Pseudo code:
> 
> procedure Fly(o: TObject);
> begin
>   case o is
>     TButton: TButton(o).foo;
>     TControl: TControl(o).bar;
>     TComponent: TComponent(o).meh;
>     nil: Msg;
>   else Run;
>   end;
> end;
> 
> The gain versus "if o is then..." is that the compiler warns if the
> case statements are not sorted and can optimize the checks.
> 
> For example the above code could be converted to:
> 
> procedure Fly(o: TObject);
> var
>   tmp: TClass;
> begin
>   if o<>nil then
>   begin
>     tmp:=o.ClassType;
>     repeat
>       if tmp=TButton then
>       begin
>         TButton(o).foo;
>         break;
>       end else if tmp=TControl then
>       begin
>         TControl(o).bar;
>         break;
>       end else if tmp=TComponent then
>       begin
>         TComponent(o).meh;
>         break;
>       end;
>       tmp:=tmp.ClassParent;
>       if tmp=nil then
>       begin
>         Run;
>         break;
>       end;
>     until false;
>   end else
>     Msg;
> end;
> 
> What do you think?
> 
> 
> Mattias
> _______________________________________________
> fpc-devel maillist  -  fpc-devel at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel


More information about the fpc-devel mailing list