I am new vavr so I don't know if I am missing some basic stuff but i am doing pattern matching which Java does not have right now. After debugging I realized that vavr matches all the Cases but will not execute the value if a Supplier is provided if the case condition does not match. Is that right?
for eg:
public Enum Days{
MONDAY,
TUESDAY...
}
String s = Match(days).of(
Case($(Days.MONDAY), "monday"),
Case($(Days.TUESDAY), "tuesday")
);
In the above example if days = MONDAY it calls the CASE method passes the enum value and checks if there is a match. In this case its a match so it will return "monday". I was hoping the pattern matching will be terminated since we got the match. But it turns out it goes inside Case method again for TuESDAY also , the pattern does not match so the value remains "monday" but I was wondering is there a way to stop the pattern matching once the condition is met.
Vavr Match
will stop at the first matching Case
and will return the associated value.
What you are experiencing is just standard Java behavior. Arguments are eagerly evaluated before being passed to a method, so, when you write
Case(Pattern, retValExpression)
and retValExpression
is an expression, the retValExpression
expression will be eagerly evaluated before even passing it over to the API.Case
factory method. If you want the retValExpression
expression to be lazily evaluated only when the Case
is matching, you need to convert it to a Supplier
by creating a lambda expression:
Case(Pattern, () -> retValExpression)
In this case, the lambda expression () -> retValExpression
will only be evaluated when the corresponding Case
is matching.
If your problem lies with the Pattern
expressions getting evaluated eagerly, you can apply the same technique to convert them to lazy evaluation by supplying a lambda for a Predicate
:
Case($(value -> test(value)), () -> retValExpression)