Typed variants of primitives
Stephen Colebourne
scolebourne at joda.org
Mon Nov 30 00:13:00 UTC 2020
I wanted to raise a concept that I don't remember seeing as part of
the valhalla work so far, and I'll do so via a java.time.* example.
`java.time.*` contains a `Year` value-based class that effectively
acts as a "typed int" with two key purposes:
- to provide additional type safety if desired for the concept of "year"
- to restrict the valid int values to -999_999_999 to 999_999_999.
`LocalDate` has a method `getYear()`, but it returns an `int`, rather
than the `Year` class. Was this a mistake? Not really, it was a
pragmatic decision to say that most users of the API would want the
int, not the `Year` value type (and the performance hit of an
additional object).
In an ideal valhalla world, `LocalDate.getYear()` would be changed to
return `Year`, not `int`, and this change would be entirely backwards
compatible. The implication is that a valhalla `Year` value type could
be freely unboxed to an `int`.
Now of course, it is almost certainly pie-in-the-sky to try and make
something this backwards compatible. But what about new types? In API
design terms, there is appeal in defining a type that restricts the
valid set of ints, for example a `PositiveInt` value type. But without
the associated boxing/unboxing to `int` and maths operator-overloading
it is generally more pain than it is worth to design an API that way.
Has this concept been considered?
Stephen
More information about the valhalla-dev
mailing list