java - 将元组内的选项与 Vavr 进行匹配

标签 java pattern-matching vavr

使用Vavr的类型,我创建了一对 Some s:

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

我想使用 Vavr 的匹配表达式获取整数 12;这就是我目前的做法:

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/

相关文章:

java - 获取每个单词的第一个字符及其在句子/段落中的位置

java - java.io 包中的缓冲如何优化性能

regex - 在 sed 替换中用 RegEx 替换模式

java - 如何使用可选项实现这个嵌套流程?

java - 使用Java和Vavr使用功能样式异常处理的逻辑

java - 无法实例化类型 ResteasyClientBuilder

当我尝试向客户添加另一个产品时发生 java.lang.StackOverflowError

algorithm - KMP算法的最佳和最差时间复杂度是多少

regex - 正则表达式的时间复杂度和模式查找中允许抖动

java - 返回泛型类型时出现 ClassCastException