Sign in Join
Wiki copytemporary

Nullable types/fi: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Nullable types/fi

OldNewLine
1+Tyhjennettävät tyypit (Nullable types) ovat sellaisia tietotyyppejä, joilla ei välttämättä ole arvoa (voidaan määrätä). Yksi tällainen tyyppi Pascalissa on [[Pointer/fi|pointer-tyyppi]], jolla voi olla [[Nil/fi|nil]] arvo, mikä tarkoittaa, että sitä ei ole osoitettu mihinkään tiettyyn osoitteeseen. Sama käyttäytyminen voidaan toteuttaa käyttämällä [[Generics/fi|geneerisiä tyyppejä]] ja advanced record tietueita, joissa on [[Operator overloading/fi|operaattorin ylikuormitus]].
2+
3+``` pascal
4+unit Nullable;
5+
6+{$mode delphi}{$H+}
7+
8+interface
9+
10+uses
11+ Classes, SysUtils;
12+
13+type
14+ TNullable<T> = record
15+ private
16+ FHasValue: Boolean;
17+ FValue: T;
18+ function GetValue: T;
19+ procedure SetValue(AValue: T);
20+ public
21+ procedure Clear;
22+ property HasValue: Boolean read FHasValue;
23+ property Value: T read GetValue write SetValue;
24+ class operator Implicit(A: T): TNullable<T>;
25+ class operator Implicit(A: Pointer): TNullable<T>;
26+ end;
27+
28+implementation
29+
30+{ TNullable }
31+
32+function TNullable<T>.GetValue: T;
33+begin
34+ if FHasValue then
35+ Result := FValue
36+ else
37+ raise Exception.Create('Variable has no value');
38+end;
39+
40+procedure TNullable<T>.SetValue(AValue: T);
41+begin
42+ FValue := AValue;
43+ FHasValue := True;
44+end;
45+
46+procedure TNullable<T>.Clear;
47+begin
48+ FHasValue := False;
49+end;
50+
51+class operator TNullable<T>.Implicit(A: T): TNullable<T>;
52+begin
53+ Result.Value := A;
54+end;
55+
56+class operator TNullable<T>.Implicit(A: Pointer): TNullable<T>;
57+begin
58+ if A = nil then Result.Clear
59+ else raise Exception.Create('Pointer value not allowed');
60+end;
61+
62+end.
63+```
64+
65+Tyhjennettävät tyypit (Nullable types) voidaan määritellä esimerkiksi näin:
66+
67+``` pascal
68+NullableChar = TNullable<Char>;
69+NullableInteger = TNullable<Integer>;
70+NullableString = TNullable<string>;
71+```
72+
73+## Katso myös
74+
75+- [[How to use nullable types/fi|How to use nullable types]]
76+
77+## Ulkopuoliset linkit
78+
79+- [Nullables in Free Pascal and Delphi](https://www.arbinada.com/en/node/1439)
80+
81+---
82+*From the Free Pascal wiki, page "Nullable types/fi", as it stood on 2022-08-06 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history