Search code examples
scalapattern-matchingwildcardcase-class

Is it possible to use named parameter for Scala case-class matching?


Suppose there is a Scala case-class Point

case class Point(x: Int, y: Int)

One can use a wildcard for matching:

val p = new Point(1,2)
val inRightHalfPlane = p match {
  case Point(x, _) if x>0 => true
  case _ => false
}

However, if the number of members increase, one will need to use more wildcards _:

case class Point(
  x0: Int,
  x1: Int,
  x2: Int,
  x3: Int,
  x4: Int,
)


val flag = p match {
  case Point(x,_,_,_,_,) if x>0 => true
  ......
}

Is there any syntax sugar like the following code?

val flag = p match {
  case Point(x0=x) if x>0 => true
  ......
}

Solution

  • You can define custom unapply

      case class Point(
                        x0: Int,
                        x1: Int,
                        x2: Int,
                        x3: Int,
                        x4: Int,
                      )
    
      object PositiveFirst {
        def unapply(p: Point): Option[Int] = if (p.x0 > 0) Some(p.x0) else None
      }
    
      val p: Point = ???
    
      val flag = p match {
        case PositiveFirst(x) => true
    //      ......
      }