2

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.

4

1 回答 1

2

我将通过以下方式使用(*)( *) 结合:Tuple.applyAPI.For

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

(*):为两个参数重载提供链接以符合您的示例

于 2019-06-13T21:27:50.280 回答