gpt4 book ai didi

scala - 寻找在 Scala 中进行模式匹配时如何使用 "@_*"的示例

转载 作者:行者123 更新时间:2023-12-04 11:45:25 25 4
gpt4 key购买 nike

我一直在搜索,但找不到任何示例在模式匹配案例类时演示 @_* 的用法。

下面是我所指的那种应用程序的一个例子。

def findPerimeter(o: SomeObject): Perimeter = o match {
case Type1(length, width) =>
new Perimeter(0, 0, length, width)
case Type2(radius) =>
new Perimeter(0, 0, 2*radius, 2*radius)
...

case MixedTypes(group @_*) => {
\\How could @_* be used to check subpatterns of group?
}

}

如果有人可以向我展示一些示例或将我指向一个包含一些示例的网页,那就太好了。

谢谢

最佳答案

请记住,像

Type2(3.0) match {
case t2 @ Type2(radius) => //...
}

绑定(bind) radius到值 3.0并绑定(bind) t2到被匹配的 Type2 的实例。

使用您的示例:
def findPerimeter(o: SomeObject): Perimeter = o match {
case Type1(length, width) => new Perimeter(0, 0, length, width)
case Type2(radius) => new Perimeter(0, 0, 2*radius, 2*radius)
// ...
// assume that Perimeter defines a + operator
case MixedTypes(group @ _*) => group.reduceLeft(findPerimeter(_) + findPerimeter(_))

}

在这里, group绑定(bind)到 SomeObject 的序列s 定义 MixedTypes .您可以将其视为构造函数参数用于混合类型的序列。

关于scala - 寻找在 Scala 中进行模式匹配时如何使用 "@_*"的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2316037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com