Typed variants of primitives
scolebourne at joda.org
Wed Dec 2 22:57:46 UTC 2020
On Wed, 2 Dec 2020 at 14:17, Brian Goetz <brian.goetz at oracle.com> wrote:
> Then if the user wants an int, they could say:
> int y = date.getYear().val()
> But, even that `.val()` might feel like noise; what you're appealing to a is a _primitive widening conversion_ (JLS 5.1.2) from Year to int. Since the range of Year is (isomorphic to) a restriction of int, this is a reasonable thing to want, that Year could define such a conversion. This would get you to:
> int y = date.getYear() // implicit primitive widening conversion
> We are indeed investigating how we might generalize JLS 5.x to support such things.
> Very short answer: Yes, this is all being considered!
> On 11/29/2020 7:13 PM, Stephen Colebourne wrote:
> 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?
More information about the valhalla-dev