St.Antario
St.Antario

Reputation: 27375

Omiting parameters in pattern matching in scala

I have the following case class:

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

Now in pattern matching I want to just match the class, not all this parameters:

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

Actually I dont care about params values. Is there a way to write it more concisely?

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

Upvotes: 2

Views: 844

Answers (2)

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23502

You could extract the inner class like this:

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

Alternatively you could just ignore the values by using underscores:

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

Upvotes: 2

oxbow_lakes
oxbow_lakes

Reputation: 134260

Use this pattern

case Some(c: Cls) => 

As follows:

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

defined class 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)

Upvotes: 4

Related Questions