var input = Tuple(Some(1), Some(2));
我想使用 Vavr 的匹配表达式获取整数 1
和 2
;这就是我目前的做法:
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")
);
这可以工作并返回“1/2”
,但让我担心,因为我在两个Some
上调用了不安全的get
方法。
我宁愿让匹配表达式将输入
分解到提取最内部整数的位置。
Vavr 用户指南中的这条注释让我怀疑这是否可能:
⚡ 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.
但我仍然很好奇是否有一种更优雅、类型安全的方法来分解嵌套值input
。
最佳答案
我会使用Tuple.apply
(*) 与 API.For
结合(*) 通过以下方式:
var output = input.apply(API::For)
.yield((i1, i2) -> i1 + "/" + i2)
.getOrElse("No match");
(*):提供两个参数重载的链接以符合您的示例
关于java - 将元组内的选项与 Vavr 进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56505036/