0

Vavr User Guide refers to the following piece of code while discussing its named parameters feature:

Named Parameters

Vavr leverages lambdas to provide named parameters for matched values.

 Number plusOne = Match(obj).of(
     Case($(instanceOf(Integer.class)), i -> i + 1),
     Case($(instanceOf(Double.class)), d -> d + 1),
     Case($(), o -> { throw new NumberFormatException(); }) );

Could someone please elaborate on where the named parameters are in play here and how they are used? Thank you in advance.

Simeon Leyzerzon
  • 18,658
  • 9
  • 54
  • 82

1 Answers1

0

I think what they mean is, without Vavr, you would have to cast the matched object to the matched type (e.g. in line 2, you would need to cast to Integer). With Vavr, in the lambda, the parameter is the matched object in the correct type already, you didn't need to cast it.

int withoutVavr(Object obj) {
  if (obj instanceof Integer) {
    return ((Integer) obj) + 42;
  } else if (obj instanceof String) {
    return ((String) obj).concat("obj is just an Object until I cast it").length();
  }
  throw new NumberFormatException();
}

int withVavr(Object obj) {
  return Match(obj).of(
      Case($(instanceOf(Integer.class)), i -> i + 42),
      Case($(instanceOf(String.class)),
          blabla -> blabla.concat("blabla is a string, I did not need to cast it; also, I could rename it to blabla thanks to lambdas, without writing the tedious 'String blabla = (String) obj'").length()),
      Case($(), o -> {
        throw new NumberFormatException();
      }));
}

Hope this clarifies/helps.

Sir4ur0n
  • 1,753
  • 1
  • 13
  • 24