Null-checked reference types
Quirin Schroll
qs.il.paperinik at gmail.com
Wed Aug 7 15:44:36 UTC 2024
On Wednesday, 7 August 2024 at 14:34:00 UTC, IchorDev wrote:
> On Wednesday, 7 August 2024 at 10:13:05 UTC, Quirin Schroll
> wrote:
>> Reference types are nullable, yet most of the time, actual
>> references aren’t null and expected to be non-null.
>
> Well that’s why associative arrays implicitly allocate
> themselves. I don’t think that would work for classes though…
>
>> 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.
>
> Uh yeah… we should be preventing that.
>
>> 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.
>
> Interesting. Do people who use those languages actually like
> that?
I don’t know, I’m neither a Zig nor Kotlin Dev.
I did some C# and like its direction with non-nullable types,
but unfortunately, they have to be backwards compatible, which
means `?` types are treated as suggestions. There was a C#
proposal to add `!!` parameters which makes them run-time checked
for null. It was rejected, but I don’t remember why.
C#’s nullability stuff as one downside: `T?` means two different
things depending if `T` is a value or reference type, and because
C# has generics, not templates, in a generic context, using `T?`
means: Nullable if `T` is a reference type, but non-nullable if
`T` is a value type. However, if `T` is restricted to value
types, it means nullable `T`.
>>> 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.
>
> Well there you go, maybe for value types we need something like
> the range interface but for nullability? And then for reference
> types can just do `is null`.
The whole goal of nullable annotations / types is to make the
compiler find the places where `is null` is needed and where it’s
not needed.
More information about the dip.development
mailing list