在scala中忽略模式匹配中的参数

时间:2017-03-20 10:18:05

标签: scala pattern-matching

我有以下案例类:

case class Cls(a: Int, b: Long, c: String, f: Int, d: Long, e: Long)

现在在模式匹配中我想匹配类,而不是所有这些参数:

clsOpt match {
    case Some(Cls(a, b, c, f, d, e)) => println("matched")
}

其实我不关心params值。有没有办法更简洁地写出来?

clsOpt match {
    case Some(Cls) => println("matched") // compile-error
}

2 个答案:

答案 0 :(得分:4)

使用此模式

case Some(c: Cls) => 

如下:

 scala> case class Cls(a: Int, b: Long, c: String, f: Int, d: Long, e: Long)

定义的类Cls

scala> val x: Option[Cls] = Some(Cls(1, 2, "3", 4, 5, 6))
x: Option[Cls] = Some(Cls(1,2,3,4,5,6))

scala> x match { case Some(c: Cls) => println(s"matched: $c")  case None => }
matched: Cls(1,2,3,4,5,6)

答案 1 :(得分:2)

你可以像这样提取内部类:

clsOpt match {
  case Some(_) => println(clsOpt.get)
  case None => println("n")
}

或者你可以通过使用下划线来忽略这些值:

clsOpt match {
  case Some(Cls(_,_,_,_,_,_)) => println("matched")
}
相关问题