Match on Options inside Tuple with Vavr

Matthias Braun :

Using Vavr's types, I have created a pair of Somes:

var input = Tuple(Some(1), Some(2));

I'd like to get at the integers 1 and 2 using Vavr's match expression; this is how I currently do it:

import static io.vavr.API.*;
import static io.vavr.Patterns.$Some;
import static io.vavr.Patterns.$Tuple2;

var output = Match(input).of(
        Case($Tuple2($Some($()), $Some($())),
                (fst, snd) -> fst.get() + "/" + snd.get()),
        Case($(), "No match")
);

This works and returns "1/2" but has me worried since I call the unsafe get methods on the two Somes.

I'd rather have the match expression decompose input to the the point where it extracts the innermost integers.

This note in Vavr's user guide makes me doubt whether that's possible:

⚡ A first prototype of Vavr’s Match API allowed to extract a user-defined selection of objects from a match pattern. Without proper compiler support this isn’t practicable because the number of generated methods exploded exponentially. The current API makes the compromise that all patterns are matched but only the root patterns are decomposed.

Yet I'm still curious whether there's a more elegant, type-safe way to decompose the nested value input.

Nándor Előd Fekete :

I would use Tuple.apply(*) combined with API.For(*) in the following way:

var output = input.apply(API::For)
    .yield((i1, i2) -> i1 + "/" + i2)
    .getOrElse("No match");

(*): links are provided to the two argument overloads to conform to your example

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135196&siteId=1