Avn*_*arr 3 syntax scala pattern-matching case-class
我有一个密封的特性与各种案例类实现.我想在同一个匹配表达式上同时对多个类进行模式匹配.没有分解案例类和"|"我似乎无法做到这一点 它们之间
目前看起来像:
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
Run Code Online (Sandbox Code Playgroud)
代码中的另一个地方:
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
}
}
Run Code Online (Sandbox Code Playgroud)
让我们一步一步走到那里:
的|操作者,在图案匹配的情况下,允许定义替代的图案,在下面的形式:
pattern1 | pattern2
Run Code Online (Sandbox Code Playgroud)如果要定义与类型匹配的模式,则必须以下列形式提供模式:
binding: Type
Run Code Online (Sandbox Code Playgroud)然后应以下列形式提供两种不同类型之间的选择:
binding1: Type1 | binding2: Type2
Run Code Online (Sandbox Code Playgroud)要将单个名称绑定到两个备用绑定,您可以丢弃单个绑定的名称(使用_通配符),并使用@运算符将整个模式的名称绑定到另一个绑定,如以下示例所示:
binding @ (_ : Type1 | _ : Type2)
Run Code Online (Sandbox Code Playgroud)以下是一个例子:
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
}
}
Run Code Online (Sandbox Code Playgroud)
以下是调用时的一些示例输出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
Run Code Online (Sandbox Code Playgroud)
您可以在Scastie上玩这些示例.