Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define MyType that can contain only these values?

I have this problem: if I have, for example, these values: 'AA', 'AB', 'AC', 'BC' - can I define MyType that can contain only these values?

I want to do in mode that:

type MyType = ... ; // something
var X: MyType;
begin
  x := 'AA' ;  // is valid, 'AA' is included in X 
  X := 'SS' ;  // not valid, 'SS' not is included in X, than raise an exception.
end; 

How can I solve it? Is there some solution directly using type data?

like image 634
Marcello Impastato Avatar asked Dec 22 '22 06:12

Marcello Impastato


1 Answers

This is actually rather simple using operator overloading.

Do

type
  TMyType = record
  private
    type
      TMyTypeEnum = (mtAA, mtAB, mtAC, mtBC);
    var
      FMyTypeEnum: TMyTypeEnum;
  public
    class operator Implicit(const S: string): TMyType;
    class operator Implicit(const S: TMyType): string;
  end;

implementation

class operator TMyType.Implicit(const S: string): TMyType;
begin
  if SameStr(S, 'AA') then begin result.FMyTypeEnum := mtAA; Exit; end;
  if SameStr(S, 'AB') then begin result.FMyTypeEnum := mtAB; Exit; end;
  if SameStr(S, 'AC') then begin result.FMyTypeEnum := mtAC; Exit; end;
  if SameStr(S, 'BC') then begin result.FMyTypeEnum := mtBC; Exit; end;
  raise Exception.CreateFmt('Invalid value "%s".', [S]);
end;

class operator TMyType.Implicit(const S: TMyType): string;
begin
  case S.FMyTypeEnum of
    mtAA: result := 'AA';
    mtAB: result := 'AB';
    mtAC: result := 'AC';
    mtBC: result := 'BC';
  end;
end;

Now you can do

procedure TForm1.Button1Click(Sender: TObject);
var
  S: TMyType;
begin
  S := 'AA';                // works
  Self.Caption := S;

  S := 'DA';                // does not work, exception raised
  Self.Caption := S;
end;
like image 166
Andreas Rejbrand Avatar answered Dec 31 '22 14:12

Andreas Rejbrand