Comparing ranges with switch
Brian Goetz
brian.goetz at oracle.com
Wed Mar 13 17:40:01 UTC 2024
As an added bonus, it becomes practical to get useful exhaustiveness
checking for integral types larger than boolean, as this example with
byte shows.
On 3/13/2024 12:33 PM, David Alayachew wrote:
> 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){
>
> caseIntegeri wheni >1&&i <10->{}
>
> case42->{}
>
> default->thrownewIllegalArgumentException("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/b9cdb174/attachment-0001.htm>
More information about the amber-dev
mailing list