scala语法匹配多个案例类类型而不分解案例类

标签 scala syntax pattern-matching case-class

这个问题在这里已经有了答案:





Scala multiple type pattern matching

(1 个回答)


3年前关闭。




我有各种案例类实现的密封特征。我想为同一个匹配表达式一次对多个类进行模式匹配。如果不分解案例类和“|”,我似乎无法做到这一点它们之间

目前看起来像:

sealed trait MyTrait {
  val param1: String
  ...
  val param100: String
}

case class FirstCase(param1: String ...... param100: String) extends MyTrait
...
case class NthCase(param1: String ..... param100: String) extends MyTrait

代码中的另一个地方:
def myFunction(something: MyTrait) = {
   ...
   val matchedThing = something match {
      // this doesn't work with "|" character
      case thing: FirstCase | SecondCase => thing.param1
      ...
      case thing: XthCase | JthCase => thing.param10
   }
} 

最佳答案

让我们一步一步地去那里:

  • |运算符,在模式匹配的上下文中,允许您以以下形式定义替代模式:
    pattern1 | pattern2
    
  • 如果要定义与类型匹配的模式,则必须以以下形式提供模式:
    binding: Type
    
  • 然后应以以下形式提供两种不同类型之间的选择:
    binding1: Type1 | binding2: Type2
    
  • 要将单个名称绑定(bind)到两个替代绑定(bind),您可以丢弃单个绑定(bind)的名称(使用 _ 通配符)并使用 @ 将整个模式的名称绑定(bind)到另一个绑定(bind)。运算符,如下例所示:
    binding @ (_ : Type1 | _ : Type2)
    

  • 下面是一个例子:
    sealed trait Trait {
      def a: String
      def b: String
    }
    
    final case class C1(a: String, b: String) extends Trait
    final case class C2(a: String, b: String) extends Trait
    final case class C3(a: String, b: String) extends Trait
    
    object Trait {
      def f(t: Trait): String =
       t match {
        case x @ (_ : C1 | _ : C2) => x.a // the line you are probably interested in
        case y: C3 => y.b
      }
    }
    

    这是调用 f 时的一些示例输出:
    scala> Trait.f(C1("hello", "world"))
    res0: String = hello
    
    scala> Trait.f(C2("hello", "world"))
    res1: String = hello
    
    scala> Trait.f(C3("hello", "world"))
    res2: String = world
    

    您可以使用提供的示例 here on Scastie .

    关于scala语法匹配多个案例类类型而不分解案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52645036/

    相关文章:

    scala - 具有相同形状的案例类?

    scala - Akka 在 Play 中如何使用?

    scala - 这个案例类匹配模式是如何工作的?

    r - 长转宽格式: keep row orders and use only part of row values for newly created column names

    java - 有没有办法简化 Java 模式匹配从 POST 请求中检索两条数据?

    scala - Play Framework 2.3 中的域路由

    scala - 在 Akka/Scala 中使用带有 future 的 mapTo

    javascript - 石头剪刀布游戏错误,Javascript

    python - 使用 [ :] syntax 的 numpy 维度问题

    mysql - 将oracle脚本转换为mysql脚本