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

Ron Pressler ron.pressler at oracle.com
Fri Jan 27 14:06:37 UTC 2023



> On 27 Jan 2023, at 13:42, Red IO <redio.development at gmail.com> wrote:
> 
> 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.

It is a different concept, but the JLS treats them both as sub-concept of a single, wider one called a “narrowing conversion”, which may either succeed or fail at runtime (and there are different ways to interpret what “success" means). A pattern match between a value and a pattern is allowed when a narrowing conversion is allowed, and if it succeeds then the narrowing conversion from the value to the pattern is guaranteed to succeed (in the case of primitives, “success” here is interpreted to mean that the conversion is not lossy).

Your point about references and memory copying is also becoming outdated as classes may not represent only types whose values are always accessed by reference (Project Valhalla). So even “plain” assignments, with or without casts on user-defined classes may involve memory copies. Conversely, primitives are not necessarily copied when cast. For example, if we have `void foo(int x)`, calling `foo((int)myLong)` will not involve an additional copy (if at all, depending on how things are inlined, but now we’re at the VM implementation level, not the language specification level).

So the move here is not to conflate subtypes and primitive conversions, but rather to state that patterns operate at the higher, more general level of “narrowing conversions”, which subsumes both kinds as special cases. It says, don’t think of patterns as a subtype check, but as a narrowing conversion check (which also includes subtypes; see JLS §5.1.6)

— Ron


More information about the amber-dev mailing list