Null-checked reference types
Quirin Schroll
qs.il.paperinik at gmail.com
Wed Aug 7 10:13:05 UTC 2024
On Wednesday, 7 August 2024 at 04:17:42 UTC, IchorDev wrote:
> On Tuesday, 6 August 2024 at 14:55:46 UTC, Quirin Schroll wrote:
>> Add the following type suffixes to the language: `?` and `!`.
>
> Reference types are already nullable.
Yes, that’s the issue.
> Having a way to force them to be non-null would be nice
> (although you could just use contracts?), but I don’t think
> having to explicitly mark reference types as nullable makes
> sense.
> They’re reference types, of course they’re nullable!
Reference types are nullable, yet most of the time, actual
references aren’t null and expected to be non-null. Prime
example: `ref`. Can be null, never is expected to be in practice,
and when it happens to be null, it’s a bug. A bug not by the
language semantics, but in practical code. 100% of the time.
Instead of a contract or documentation saying they have to be
non-null, the best way is to have the type system enforce it at
compile-time. Just to mention two, Kotlin and Zig default to
non-nullable references / pointers. You have to annotate nullable
ones and handle the null case.
If your module has a default of reference types being
non-nullable (because almost all the time, they’re expected not
to be null), of course you have to mark them as nullable in case
they are. If your module default is reference types being
nullable, you have to annotate non-nullable ones.
> Having nullability for value types might be nice too, but again
> it’s something you can already achieve in other ways.
Yes, optionals, which aren’t great to use. Having worked with C#,
which has core-language nullable value types, I can tell you, it
makes it really nice to work with them. If an `indexOf` function
returns `size_t?` (or even better: some `index_t?` which hooks
into the null semantics so that it reserves `size_t.max` for its
null state), it’s clear that the case of whatever you’re seeking
might not be there as to be accounted for.
More information about the dip.development
mailing list