[fpc-devel] case is
Mattias Gaertner
nc-gaertnma at netcologne.de
Wed Mar 23 13:44:36 CET 2022
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
More information about the fpc-devel
mailing list