是否有任何选项可以对 vavrs 集合应用对象分解?
即类似于 scala 中的代码片段:
val x = List(1, 2, 3)
val t = x match {
case List(a, b, c) => (a, b, c)
}
(在此示例中,我们将列表转换为元组)
我在这里看到了一些与我的案例类似的例子 https://github.com/vavr-io/vavr/issues/1157但看起来当前的语法不同,甚至是不可能的。
最佳答案
Vavr 列表与许多功能程序一样,由头(单个元素,称为 Cons)和尾(另一个列表)组成,可以匹配第一个元素(不是最后一个,除非通过反转列表) ),尽管这会比 Scala/Haskell 更冗长。另外,虽然您可以匹配前 3 个元素,但您只能捕获第一个:
var t = Match(x).of(
Case($Cons($(), $Cons($(), $Cons($(), $()))), (a, tail) -> Tuple(a, tail.head(), x.get(2)))
);
Vavr documentation of Pattern Matching and its limitations :
The current API makes the compromise that all patterns are matched but only the root patterns are decomposed.
编辑:如果您想要列表中正好有 3 个元素,那么您需要确保第三个元素之后的尾部是一个空列表(称为 Nil):
var t = Match(x).of(
Case($Cons($(), $Cons($(), $Cons($(), $Nil()))), (a, tail) -> Tuple(a, tail.head(), x.get(2)))
);
关于java - Vavr 中列表上的模式匹配对象分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55398734/