$ \def\Vec#1{\mathbf{#1}} \def\vt#1{\Vec{v}_{#1}(t)} \def\v#1{\Vec{v}_{#1}} \def\vx#1{\Vec{x}_{#1}} \def\av{\bar{\Vec{v}}} \def\vdel{\Vec{\Delta}} $

Harald Kirsch

about this blog
2024-06-28

Java Wishlist: Non Null Type Definitions

Previous entries in my Java Wishlist series:
  1. Union Types
  2. Thread Safety

I hope I don't need to cite the billion dollar mistake or mention that Typescript has explicit null typing?

Neither do I need to mention that there are various annotation frameworks which allow to annotate a field or parameter as to whether it may be null or not. Though having half a gazillion frameworks suggests that you want to use none of them for compatibility reasons.

The consensus, at least in the "strong typing" community, seems to be that it is a good thing to explicitly declare whether a value may be null or not.

A partial solution is on the way

Luckily we have a draft JEP, "Null-Restricted Value Class Types", which will provide a partial solution. For value classes.

In very short terms: an object of a value class "lacks identity", meaning (my paraphrasing) the compiler may create byte-for-byte copies if it seems useful, like creating an object copy on the stack rather than using an object reference. Much like an int, as opposed to Integer.

The syntax for non-null values, so far, is an exclamation mark suffix on the type:

Complex! ipi = new Complex(0, Math.PI);

I wish we could have this for every type, not only for value types.