Difference between revisions of "Nullable types"

From Free Pascal wiki
Jump to navigationJump to search
(Created page with "Nullable types are types which can have no value (can be unassigned). One such type in Pascal is Pointer type which can have nil value which means that it isn't assigned to an...")
 
(reference Nil)
Line 1: Line 1:
Nullable types are types which can have no value (can be unassigned). One such type in Pascal is Pointer type which can have nil value which means that it isn't assigned to any specific address. Same behavior can be implemented using generic types and advanced records with operator overloading.
+
Nullable types are types which can have no value (can be unassigned).
 +
One such type in Pascal is Pointer type which can have [[Nil|<syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight>]] value which means that it isn't assigned to any specific address.
 +
Same behavior can be implemented using generic types and advanced records with operator overloading.
  
 
<syntaxhighlight lang="pascal">
 
<syntaxhighlight lang="pascal">
Line 70: Line 72:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==External links==
+
== External links ==
  
 
* [https://www.arbinada.com/en/node/1439 Nullables in Free Pascal and Delphi]
 
* [https://www.arbinada.com/en/node/1439 Nullables in Free Pascal and Delphi]
  
 
[[Category:Pascal]]
 
[[Category:Pascal]]

Revision as of 12:07, 21 April 2019

Nullable types are types which can have no value (can be unassigned). One such type in Pascal is Pointer type which can have nil value which means that it isn't assigned to any specific address. Same behavior can be implemented using generic types and advanced records with operator overloading.

unit Nullable;

{$mode delphi}{$H+}

interface

uses
  Classes, SysUtils;

type
  TNullable<T> = record
  private
    FHasValue: Boolean;
    FValue: T;
    function GetValue: T;
    procedure SetValue(AValue: T);
  public
    procedure Clear;
    property HasValue: Boolean read FHasValue;
    property Value: T read GetValue write SetValue;
    class operator Implicit(A: T): TNullable<T>;
    class operator Implicit(A: Pointer): TNullable<T>;
  end;

implementation

{ TNullable }

function TNullable<T>.GetValue: T;
begin
  if FHasValue then
     Result := FValue
  else
    raise Exception.Create('Variable has no value');
end;

procedure TNullable<T>.SetValue(AValue: T);
begin
  FValue := AValue;
  FHasValue := True;
end;

procedure TNullable<T>.Clear;
begin
  FHasValue := False;
end;

class operator TNullable<T>.Implicit(A: T): TNullable<T>;
begin
  Result.Value := A;
end;

class operator TNullable<T>.Implicit(A: Pointer): TNullable<T>;
begin
  if A = nil then Result.Clear
  else raise Exception.Create('Pointer value not allowed');
end;

end.

Then you can define nullable types like:

NullableChar = TNullable<Char>;
NullableInteger = TNullable<Integer>;
NullableString = TNullable<string>;

External links