Comparing ranges with switch

David Alayachew davidalayachew at gmail.com
Wed Mar 13 16:33:11 UTC 2024


Well, what Brian and RedIO are suggesting would be more like this.

byte b = 123;

System.out.println
(
   switch (b)
   {

      case -128..-1  -> "It's negative!";
      case 0         -> "It's zero!";
      case 1..127    -> "It's positive!";

   }
)
;

The difference is, in this example, it would be EXHAUSTIVE, NO DEFAULT
CLAUSE NECESSARY. Your example requires either a default or a type pattern
to be exhaustive, as do basically all switches that use when clauses.

That exhaustiveness is powerful because -- patterns compose. For example,
if you have a complex set of number checks, this switch will tell you if
you left a value out. That is the power of exhaustiveness. When you combine
it with composition, you can take an arbitrarily complex domain, and the
compiler will let you know if you missed a case.

On Wed, Mar 13, 2024 at 12:13 PM Josiah Noel <josiahnoel at gmail.com> wrote:

> we sorta have this with switch guards
>
> switch (intyMcIntFace) {
>
> case Integer i when i > 1 && i < 10 -> {}
>
> case 42 -> {}
>
>
> default -> throw new IllegalArgumentException("Unexpected value: ");
>
> }
>
> On Wed, Mar 13, 2024 at 8:16 AM Red IO <redio.development at gmail.com>
> wrote:
>
>> The switch statement saw a huge transformation over the past few
>> releases. So I was quite surprised to realize that the current switch
>> construct can't check the range of an value.
>> Example case x is between y and z.
>> I'm most likely not the first one to notice that. Is there any discussion
>> about adding some sort of range pattern? Would fit in the notion of the
>> switch checking patterns quite well.
>>
>> Great regards
>> RedIODev
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240313/7e81644b/attachment.htm>


More information about the amber-dev mailing list