[External] : Re: Draft JEP on Primitive types in patterns, instanceof, and switch

Red IO redio.development at gmail.com
Fri Jan 27 13:42:36 UTC 2023


But reference type casts are fundamentally different from primitive number
type casts.
When we cast rather with instanceof or just an plain old cast we don't
alter memory at all. We simply get a reference to the previous memory
location with a more specific type. Primitives are copied when casted (at
least as far as I know). Sure the cost of copying a primitive is equal or
smaller than creating a reference but the concept is a different one.
byte is not a subtype of int.
It's more like (not valid syntax):
int i = new int(5);
byte b = new byte(i);
They are not related in their types besides the (valid) simple conversions
the compiler can do. It's like we would allow:
StringBuilder b = (StringBuilder) "original";
Because there is an available conversion between them. Actually some
languages like C# do that. But I don't think Java should go that route.

Great regards
RedIODev

On Fri, Jan 27, 2023, 13:29 Ron Pressler <ron.pressler at oracle.com> wrote:

> Because, at least the way I read it — and perhaps the motivation needs to
> be clarified — the point is not so much how to just solve the problem of
> primitive ranges, but how to best understand patterns. Patterns are a
> language feature; widening and narrowing conversions for both references
> and primitives — with or without explicit casts — are also a language
> feature.
>
> The interesting insight in the proposal is about how the patterns language
> feature interacts with the narrowing conversion language feature. It points
> out that patterns makes narrowing reference conversion (JLS §5.1.6), aka
> “downcasts”, safe for reference types, and so it’s a reasonable
> generalisation to have patterns also make narrowing primitive conversions
> (JLS §5.1.3) safe as well. If patterns are a “narrowing conversion
> safeifier” language feature, they should work with all of the language’s
> narrowing conversions.
>
> — Ron
>
> > On 27 Jan 2023, at 11:21, Red IO <redio.development at gmail.com> wrote:
> >
> > I don't see why we need a language change here. Why not add safecast
> methods and is in bounds methods in the primitive wrapper classes. Like:
> > Byte.isInBounds(56L)
> > And
> > byte b = Byte.castOrThrow(56L);
> > Or
> > Optional<Byte> b = Byte.cast(56L);
> > Of cause the latter one would be quite inefficient in the current (pre
> Valhalla) world.
> >
> > I don't see many cases where someone might switch on a primitive and
> have many cases like in the examples (float to int, long, byte..)
> >
> > Great regards
> > RedIODev
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230127/75315dab/attachment.htm>


More information about the amber-dev mailing list