Forum > General

Nullable and Immutable types

(1/4) > >>

lainz:
Hi, several programming languages supports one time assignable constants (say to store the result of a function call) and as well nullable types.

In the wiki is described how to create a nullable type.
https://wiki.freepascal.org/Nullable_types

How this example can be extended to support one time assignments?

The assignment can be prevented at compile time in some way, or it will work only at runtime?

Peter H:
So far I see here: https://wiki.freepascal.org/How_to_use_nullable_types the nullable types must be explicitely programmatically cleared before first usage.
This is because there is no constructor called automatically in pascal.
So you could add code to the nullable type that assignment is only possible if clear.
(Im unsure how to prevent multiple clearing and reassignement)
I think this must happen at runtime because the compiler can impossibly know at compile time if an assignment is the first assignment, if a program has multiple conditional paths.

lainz:
I see only at runtime... ok, better than nothing.

Maybe adding another boolean, but again that will be cleared with the clear option that's needed to initialize it...  ::)

Peter H:
Just an idea, I have not done it, but I think it is possible:
This could be a solution: https://wiki.freepascal.org/FPC_New_Features_3.2.0#Management_operators_for_record_types

Using this, the "Clear" Flag can be initialized at time of variable definition.
Programmatical clearing is not necessary then and if the Clear flag is private and Clear procedure deleted,  impossible.

Kays:

--- Quote from: Peter H on January 03, 2021, 12:00:13 am ---[…] https://wiki.freepascal.org/How_to_use_nullable_types the nullable types must be explicitely programmatically cleared before first usage. […]
--- End quote ---
Well, de facto the FHasValue of the nullable types is zeroed, so virtually “initialized” with false, thus it isn’t actually required, but nevertheless clean programming.


--- Quote from: Peter H on January 03, 2021, 12:00:13 am ---[…] This is because there is no constructor called automatically in pascal. […]
--- End quote ---
Also, that page was written over 2 years ago. Meanwhile, FPC 3.2.0 has been released, so (not using classes) one could use management operators for extended records now. This will eliminate the requirement to “manually” invoke some initialization routine when a variable enters scope.


--- Quote from: lainz on January 03, 2021, 12:03:18 am ---I see only at runtime... ok, better than nothing. […]
--- End quote ---
Well, it’s just in trunk for now, but you can probably build something with generics with constants parameters.

Navigation

[0] Message Index

[#] Next page

Go to full version