gpt4 book ai didi

scala - 匹配 “fallthrough” : executing same piece of code for more than one case class?

转载 作者:行者123 更新时间:2023-12-04 17:55:16 24 4
gpt4 key购买 nike

我在 Scala 中有一个匹配不同案例类的函数,但在每次匹配时执行相同的代码。有没有“落空”的可能?或者另一种很好的方式来编写下面的代码而不重复代码并且不定义函数?

symbol match {
case Times(a,b) => //some code using a and b
case Plus(a,b) => //same code as above
case Div(a,b) => //again same code as above
}

这也是一个非常相似的问题“Match "fallthrough": executing same piece of code for more than one case?”,不同之处在于我希望匹配案例类。

最佳答案

您可以编写自己的提取器来组合这三种情况并将它们变成一个元组:

  object BinOp {
def unapply(op: Op) = op match {
case Times(a, b) => Some(a, b)
case Plus(a, b) => Some(a, b)
case Div(a, b) => Some(a, b)
}
}

symbol match {
case BinOp(a, b) =>
}

关于scala - 匹配 “fallthrough” : executing same piece of code for more than one case class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15019849/

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