Switch on several values
Tagir Valeev
amaembo at gmail.com
Wed Sep 27 15:00:52 UTC 2023
On Wed, Sep 27, 2023 at 4:18 PM Brian Goetz <brian.goetz at oracle.com> wrote:
> As an example of a "the simple cases are very pretty", I give you a world-class FizzBuzz:
>
> Function<Integer, String> fizzbuzz =
> x -> switch (x % 3, x % 5) {
> case (0, 0) -> "FizzBuzz";
> case (0, _) -> "Fizz";
> case (_, 0) -> "Buzz";
> default -> Integer.toString(x);
> };
This is basically a syntactic sugar for an unnamed tuple. I think,
Java is not going to the unnamed tuples direction, as we have named
ones (records). So it should be enough. We just need constant
patterns:
record Rems(int by3, int by5) {}
Function<Integer, String> fizzbuzz =
x -> switch (new Rems(x % 3, x % 5)) {
case Rems(0, 0) -> "FizzBuzz";
case Rems(0, _) -> "Fizz";
case Rems(_, 0) -> "Buzz";
default -> Integer.toString(x);
};
In future, with custom matchers, we'll be able to do it even better.
With best regards,
Tagir Valeev.
More information about the amber-spec-experts
mailing list