Question on Primitive Types in Patterns
Deepak Vohra
dvohra16 at gmail.com
Fri Sep 5 13:15:30 UTC 2025
The *Integer* can't auto-box *byte*; therefore, it is not pattern dominance.
On Fri, Sep 5, 2025 at 9:02 AM Deepak Vohra <dvohra16 at gmail.com> wrote:
> Are you using a Java version that supports pattern matching for switch
> (JDK 17+ as a preview feature, standardized in JDK 21)? Or, it is a bug.
>
> On Fri, Sep 5, 2025 at 7:09 AM Simon Ritter <sritter at azul.com> wrote:
>
>> Hi,
>> I've been giving a presentation on Patterns in the Java language and
>> including some puzzles. The recent inclusion of Primitive Types in
>> Patterns has provided some interesting material. I currently have one
>> puzzle that I can't quite explain; hopefully someone on the mailing list
>> can provide clarification.
>>
>> Let's start with this simple example:
>>
>> int x = getX(); // x is 42
>>
>> switch (x) {
>> case byte b -> System.out.println("byte");
>> case int i -> System.out.println("int");
>> }
>>
>> Here we have a runtime check, which establishes that the conversion from
>> int to byte is exact, as there is no loss of information.
>>
>> If we reverse the order of the cases:
>>
>> switch (x) {
>> case int i -> System.out.println("int");
>> case byte b -> System.out.println("byte");
>> }
>>
>> The code will not compile, as the int case dominates the byte case.
>>
>> So far, so good.
>>
>> However, if we change the int case to use a wrapper class:
>>
>> switch (x) {
>> case Integer i -> System.out.println("int");
>> case byte b -> System.out.println("byte");
>> }
>>
>> the code will compile and the result is 'int'.
>>
>> If I look at JEP 507, under the section on Safety of conversions, it
>> states that "...boxing conversions and widening reference conversions
>> are unconditionally exact." The compiler is autoboxing the int, x, to
>> create an Integer object, which always matches the first case.
>>
>> What I can't explain is why the compiler does not still see this as
>> pattern dominance? No value of x will ever result in the switch
>> matching on byte so the code is unreachable.
>>
>> Thanks in advance,
>>
>> Simon.
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20250905/26c70036/attachment-0001.htm>
More information about the amber-dev
mailing list